java异常的分类
Java异常分为两种: error
Exception
, Error是无法通过修改、完善程序就可以恢复的, 通常所指的异常为Exception及其子类
Exception
分为uncheck exception
和checked exception
unchecked exception主要指Runtime Exception及其子类
,常见的有:IndexOutOfBoundException NumberFormatException NullPointerException ArithmeticException ClassCastException...
java编译器不要求程序处理这些异常,这类异常通常是程序本身问题造成。
checked exception主要指IOException CastNotFoundException...
,通常由于程序运行环境所导致
Java异常的捕获
java中那些异常需要捕获?
java中强制捕获的异常为除了error,runtime exception及其子类的异常,异常的处理有两种方式:
1.使用try catch finally
语句块处理
2. 函数签名使用Throw
声明可能抛出的异常,交给函数调用者自己去处理(函数声明的异常调用方必须处理,否则编译不会通过)
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception{
byte[] bt = toGBK("中文");
System.out.println(Arrays.toString(bt));
}
static byte[] toGBK(String s) throws UnsupportedEncodingException{
//try {
return s.getBytes("GBK");
// }catch(UnsupportedEncodingException e){
// System.out.println(e);
// return s.getBytes();
// }
//
// }
}
}
如果不捕获异常,也需要在main函数中声明异常。main()
是捕获异常的最后机会。
try
语句块中为可能出现异常的代码,如果执行完try并未出现异常,则会执行finally
中的代码块;如果try语句出现异常,则会匹配执行catch语句,如果梅伊欧匹配的catch 语句,则会执行finally 语句块,再去外面的调用者中寻找合适的catch块。