当程序运行出现意外情况时,系统会自动生成一个Exception对象来通知程序,从而实现将业务处理代码和异常处理代码分离,提供更好的可读性。
return和finally
2.1
public class TextMain {
public static void main(String[] args) {
System.out.println("返回值:"+test01());
}
public static Integer test01() {
User user = null;
try {
System.out.println(user.getName());
System.out.println("出现错误后");
return 1;
} catch (NullPointerException e) {
System.out.println("执行异常信息输出");
System.out.println(e.getMessage());
//System.exit(1);
return 2;
} finally {
System.out.println("执行 Finally");
}
}
}
class User {
private String name;
public String getName() {
return name;
}
}
finally被用来强制在return之前执行需要被执行的代码,如上代码中,在异常处理中的最后添加return语句,还是在return执行之前执行了finally中的代码。
除非出现退出虚拟机的情况。打开如上代码中的注释。控制台输出如下:
退出虚拟机后就不存在执行代码这个的说法。
2.2
public class TextMain {
public static void main(String[] args) {
System.out.println("返回值:"+test01());
}
public static Integer test01() {
User user = null;
try {
System.out.println(user.getName());
System.out.println("出现错误后");
return 1;
} catch (NullPointerException e) {
System.out.println("执行异常信息输出");
System.out.println(e.getMessage());
//System.exit(1);
return 2;
} finally {
System.out.println("执行 Finally");
return 3;
}
}
}
class User {
private String name;
public String getName() {
return name;
}
}
当程序在try、catch中如果执行到return、throw语句,将会去查看当前异常处理流中是否包含finally语句,如果包含会去执行finally语句,没有执行的话会直接执行,但是有的话会进入finally中执行,如果在finally中包含return或者throw语句,将不会跳转到try、catch中的return、throw语句。
结论:尽量不要在finally中使用return或者throw语句。
- 自定义异常
自定义异常都应该继承Exception基类,如果希望自定义Runtime异常,应该继承RuntimeException基类。定义的异常类应该包含两个构造器,一个是无参数的构造器,一个是带字符串参数的构造器,这个参数将作为异常对象的描述信息。
自定义异常:
public class AuctionException extends Exception {
public AuctionException() {
};
public AuctionException(String msg) {
super(msg);
}
}
使用自定义的异常:
public class AuctionTest {
public static void main(String[] args) {
try {
bid();
} catch (AuctionException e) {
System.out.println(e.getMessage());
}
}
public static void bid() throws AuctionException {
try {
System.out.println(1 / 0);
} catch (Exception e) {
e.printStackTrace();
throw new AuctionException("执行错误");
}
}
}
cache和throw同时使用,捕获异常记录异常信息,同时抛出异常信息给调用者处理。
处理异常的原则:
1 不要忽视异常,能在当前方法中处理,不能就throw抛给调用者处理
2 异常铺货时,应该先铺货小异常,再捕获大异常。
部分摘自疯狂英语。
3 unchecked异常和checked异常
public class TestMain {
public static void main(String[] args) {
try {
//checked异常
throw new CheckedGenericException("checked exception");
} catch (CheckedGenericException e) {
e.printStackTrace();
}
//Unchecked异常
throw new UnCheckedException("unchecked exception");
//throw new NullPointerException("not checked exception");
}
public static class CheckedGenericException extends Exception {
private static final long serialVersionUID = 1L;
public CheckedGenericException() {
}
public CheckedGenericException(String msg) {
super(msg);
}
}
public static class UnCheckedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UnCheckedException() {
}
public UnCheckedException(String msg) {
super(msg);
}
}
}