异常
定义:当程序中某些地方出错时创建的一种特殊的运行时的错误对象
成员方法:
String getMessage():获取异常信息
void printStackTrace(): 打印异常的跟踪链信息
注:异常的传播方向和方法调用的方向相反
分类
1.按继承体系分
2.检查,未检查分
JavaSe学习总结_day15
异常的处理
1.积极处理
try{
//可能出现问题的代码
}catch(异常对象){
//如果出现异常需要执行的代码
//如果什么都不写,就会"吞掉异常",将来出现什么问题都不知道
}
2.消极处理:将异常交给方法调用者处理,main方法的调用这是jvm,当异常传给jvm程序运行就结束了
public void 方法名 throws 异常类型{
}
主动产生一个异常
throw new 异常类型(String message)
public static void show(int n) {
if (n <= 0) {
throw new RuntimeException("n必须大于0");
}else{
System.out.println(n);
}
}
public static void main(String[] args) {
try {
show(0);
} catch (RuntimeException e) {
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace();
}
}
运行结果:
java.lang.RuntimeException: n必须大于0
n必须大于0
java.lang.RuntimeException: n必须大于0
at org.westos.test1.Example.show(Example.java:6)
at org.westos.test1.Example.main(Example.java:15)
有返回值的方法 与 try-catch连用出现的问题
解决方法1: 在catch也写一个return返回结果
解决方法2: 在catch中把异常重新抛出
自定义异常
class 自定义异常名 extends 异常
public class MyException extends Exception{
// 可以从构造方法传递一个异常信息
public MyException(String message) {
super(message);
}
// 可以从构造方法传递一个异常信息, 原始的异常对象
public MyException(String message, Throwable cause) {
super(message, cause);
}
}
finally块
语法:
try{
}catch(异常对象){
}finally{
//无论try块中是否出现异常都要执行finally块中内容
}
当finally遇到return
public class Test {
public static void main(String[] args) {
int r1 = test1();
System.out.println(r1);
int r2 = test2();
System.out.println(r2);
}
public static int test1() {
try {
return 10;
} catch (Exception e) {
return 50;
} finally {
return 100;
}
}
public static int test2() {
int a = 10;
try {
return a;
} catch (Exception e) {
return 50;
} finally {
++a;
}
}
}
运行结果:
100
10