异常:
-
throw:
- 定义:用于在方法中声明抛出异常的实例对象;
-
throws:
- 定义:throws关键字对外声明该方法有可能发生的异常,调用者在调用方法时必须在程序中对异常进行处理;
- 注意:使用throws抛出多个异常时各个异常之间必须使用逗号隔开;
- 实例:如果想要调用者捕获throw抛出的异常,需要在抛出异常的方法中使用throws关键字指明异常
public class DivedeByMinusException extends Exception{
public DivedeByMinusException() {
super();//调用Exception无参构造方法
}
public DivedeByMinusException(String message) {
super(message);//调用Exception有参构造方法
}
}
public class Example{
public static void main(String[] args){
//try...catch语句用于捕获异常
try{
//调用方法,传入一个负数作为除数
int result=divide(4,-2);
System.out.println(result);
}catch(DivedeByMinusException e){ //对捕获到的异常进行处理
System.out.println(e.getMessage());//打印捕获的异常信息
}
}
//divide()方法实现两个整数相除,并使用throws关键字声明抛出自定义异常
public static int divide(int x,int y) throws DivedeByMinusException{
if(y<0){
//使用throw关键字声明异常对象
throw new DivedeByMinusException("除数是负数");
}
int result =x/y;
return result;
}
}
- 编译时异常(checked 异常):
1. 定义:Exception类中除了RunTimeException类及其子类外都是编译时异常;
2. 特点:Java编译器会对其进行检查,如果出现异常就必须对异常进行处理,否则程序无法通过编译。 - 运行时异常(unchecked 异常):
1. 定义:Exception类中RunTimeException类及其子类都是运行时异常;运行时异常一般是由程序中的逻辑错误引起的,在程序运行时无法恢复。
2. 特点:Java编译器不会对其进行检查,程序中即使没有使用try…catch语句捕获异常或throws关键字声明抛出,出现也能编译通过。