自定義異常語(yǔ)法:
class 自定義異常 extends 異常類(lèi)型{ //構(gòu)造方法}
注:
自定義異常所繼承的異常類(lèi)型必須為java標(biāo)準(zhǔn)類(lèi)庫(kù)中意思相近的異常類(lèi)型,或者直接繼承于所有異常類(lèi)型的基類(lèi)(即Exception類(lèi)型)
例如:
import java.util.Scanner;class DefinedException extends Exception{ public DefinedException() { //無(wú)參構(gòu)造器 super(); } public DefinedException(String message) { //含參構(gòu)造器 super(message); }}public class Test{ public static void main(String[] args){ System.out.PRintln("請(qǐng)輸入血壓值:"); Scanner in=new Scanner(System.in); int low=in.nextInt(); int high=in.nextInt(); try { defined(high, low); } catch (DefinedException e) { System.out.println(e.getMessage()); } } public static void defined(int high,int low) throws DefinedException{ if(low>60&&high<139){ System.out.println("血壓值正常"); } else{ throw new DefinedException("血壓值異常"); } }}運(yùn)行結(jié)果:請(qǐng)輸入血壓值:50 80血壓值異常
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注