听到异常首先会想到不正常,就是错误。实际上在java中异常是有异于错误的。
- 错误(Error)与异常(Exception)的区别
- Error是不可以用代码解决的,较为严重
- Exception可以用代码去做相应的处理
- Error与Exception都有相同的父类Trowable
异常分为运行期异常(RuntimeException)和编译期异常。其中编译期异常直接继承自Exception。
- 运行期异常与编译期异常
- 运行期异常在编译时不会报错,不用强制处理
- 编译期异常在编译时会报错,需强制处理
常见的运行期异常:
- IndexOutOfBoundsException
- ClassCastException
- ArithmeticException
- NullPointerException
常见的编译期异常:
- SqlException
- IOException
处理异常:使用关键字try、catch、finally
- try:检测不安全的代码块(发现异常)
- catch:异常处理代码
- finally:不管有没有异常都会执行
- 其中catch和finally是可以省略的,try不可省略
- 可以同时有多个catch,但是catch里面的参数必须子类放在父类前面否则会报错
- 如果catch一个编译期异常,必须在try中显式的抛出编译期异常
- 如果catch和finally中出现异常,需再次处理,即在catch和finally中嵌套try、catch、finally
栗子:
import java.io.IOException;
public class TryCatchFinally {
public static void main(String[] args) {
try{
String a = null;
a.length();
System.out.println(10/0);
System.out.println("try");
throw new IOException();
}catch(RuntimeException e){
try{
String b = null;
b.length();
}catch(Throwable t){
System.out.println("catch2");
}
System.out.println("catch");
}catch(IOException e){
}finally{
System.out.println("finally");
}
}
}
finally与return
- 无异常时执行顺序 try -> finally
- 有异常时执行顺序 try -> catch -> finally
- try,catch中有return无异常时 try -> finally -> return(try中的return)
try,catch中有return有异常时 try -> catch -> finally -> return(catch中的return)
总之finally永远执行。
throw、throws关键字:其中throw是抛出异常,throws是在方法签名上声明此方法会抛出某个异常。如果在方法中出现异常有两种处理方式,在方法中使用try、catch异常;在方法签名上使用throws声明异常。如果还有其他方法调用此方法也可以使用throws层层抛出异常。
栗子:
import java.io.IOException;
public class ThrowThrows {
public static void main(String[] args) {
try{
test(12);
}catch(IOException e){
e.printStackTrace();
}
try {
test1();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void test1() throws IOException {
test(12);
}
public static void test(int a) throws IOException {
throw new IOException();
}
}
除开java中异常类库中的异常,还可以自定义异常。自定义异常继承自Exception或其子类。自定义类中一般不写其他方法,只重载需要使用的构造方法。
栗子:
public class BusinessException extends Exception {
public BusinessException() {
super();
}
public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
public BusinessException(String message) {
super(message);
}
public BusinessException(Throwable cause) {
super(cause);
}
}
总之,对于异常的正常处理,能够将异常提供给编程人员,或者是用户,使得本来已经中断了的程序以适当的方式继续运行,或者是退出,并且能够保存用户的当前操作,或者进行数据回滚,最后再把占用的资源释放掉。
645

被折叠的 条评论
为什么被折叠?



