自定义异常类并调用的步骤:
1、通过继承方式定义一个异常类
1 //继承父类 2 public class MyException extends Exception { 3 public MyException() { 4 } 5 public MyException(String msg){ 6 super(msg); 7 } 8 }
2、方法内部抛出异常
1 public class User { 2 3 private int weight ; 4 public User() { 5 } 6 public int getWeight() { 7 return weight; 8 } 9 //必须用throws来声明,否则编译器会提示“Unhandled exception type Exception”错误警告。 10 public void transfer(int weight) throws MyException{11 if(weight<100||weight>200) 12 throw new MyException("体重不达标"); 13 this.weight = weight; 14 } 15 }
MyException继承的是Exception类,属于可检查异常(checked exception),必须声明throws。
另外一篇文章后半部分有具体解释:https://www.cnblogs.com/codercql/p/13394862.html
3、异常的捕获和处理
1 import java.util.Scanner; 2 3 public class FinalTest { 4 5 public static void main(String[] args) { 6 int weight; 7 System.out.println("输入体重:"); 8 Scanner input = new Scanner(System.in); 9 weight=input.nextInt(); 10 User user = new User(); 11 try {//使用try-catch来捕获异常 12 user.transfer(weight);//调用方法,如果抛出异常,若类型匹配那么catch捕获执行内部代码 13 }catch(MyException e) { 14 System.err.println(e.getMessage()); 15 //执行完毕后不返回try后面地语句,直接顺序执行 16 } 17 System.out.println("继续..."); 18 } 19 20 }
运行结果:
异常处理注意点:
- 如果方法没有在父类中声明异常,就不能在子类中对其进行继承来声明异常。
- catch块中异常被指定的顺序很重要,如果父类的catch块出现在子类catch块之前就会出现编译错误。
try { // }catch (ArithmeticException e) { //子类异常出现在前 }catch (Exception e) { // }
- 同样的代码处理多个异常,用竖线隔开,其中之一被捕获,就执行代码。
try { // }catch (ArithmeticException | InputMismatchException e) { System.err.println("出现错误:被除数和除数必须是整数,"+"除数不能为零。"); System.out.println(e.getMessage()); }
- printStackTrace()方法的意思是:在命令行打印异常信息在程序中出错的位置及原因。
- getMessage()返回描述该异常对象的信息。
//执行完毕后不返回try后面的语句,直接顺序执行