33.1Throwable是异常与错误的超类
- Exception:轻微
- error:都是jvm所在的系统发生的,系统级别的问题
33.2 Exception
33.3 throw关键字:抛出异常
- 在方法内部抛出异常对象
33.4 throws关键字:
- 用于方法声明上,标明此方法可能出现异常
public static void main(String[] args) throws Exception{
int[] arr = null;
method(arr);
}
public static int method(int[] arr) throws Exception{
if(arr.length < 3 || arr == null){
throw new Exception("传递参数不存在");
}else if(arr.length == 0){
throw new Exception("数组长度不可为0");
}
return arr[3];
}
33.5 try...catch...finally
- 若捕捉到异常仍然会执行程序。
- try......catch中的catch捕获的异常是有顺序的概念的,越高级的越在下面。
public static void method(int[] arr) {
try {
System.out.println(arr[0]);
} catch (NullPointerException e) {
System.out.println(e);
} finally {
System.out.println("这里的代码必须执行");
}
System.out.println("over");
}
33.6 编译时异常&运行时异常
- 运行时异常不可以捕捉只能抛出,因为其本身就不该发生。
33.7 异常在父类和子类之间
- 父类如果抛出异常,子类重写之后可以不用抛出异常
- 子类如果抛出异常,抛出的异常不能大于父类的异常
- 父类没有抛出异常,子类不能抛出异常,只能try...catch处理
class Fu{
public void function()throws Exception{ ... }
}
class Zi{
public void function()throws RuntimeException{ ... }
}
33.8 Throwable类方法
String getMessage(); 对异常信息的详细描述
String toString(); 对异常信息的间断描述
void printStackTrace(); 推荐()将异常信息追踪到标准的错误流,JVM默认调用的也是这个方法,可以看到具体的位置
33.9 自定义异常类
public class MyException extends Exception(){
public MyException(){
......
}
public MyException(String s){
super(s);
}
}
扫描二维码关注公众号,回复:
5078444 查看本文章