自定義異常語法:
class 自定義異常 extends 異常類型{ //構(gòu)造方法}
注:
自定義異常所繼承的異常類型必須為java標(biāo)準(zhǔn)類庫中意思相近的異常類型,或者直接繼承于所有異常類型的基類(即Exception類型)
例如:
import java.util.Scanner;class DefinedException extends Exception{ public DefinedException() { //無參構(gòu)造器 super(); } public DefinedException(String message) { //含參構(gòu)造器 super(message); }}public class Test{ public static void main(String[] args){ System.out.PRintln("請輸入血壓值:"); 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é)果:請輸入血壓值:50 80血壓值異常
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注