Java异常
一、try__catch异常处理
try{
//1、try块中放可能发生异常的代码。
//2、如果执行完try且不发生异常,则接着去执行finally块和finally后面的代码(如果有的话)。
//3、如果发生异常,则尝试去匹配catch块。
}catch(SQLException SQLexception){
//1、每一个catch块用于捕获并处理一个特定的异常,或者这异常类型的子类。Java7中可以将多个异常声明在一个catch中。
//2、catch后面的括号定义了异常类型和异常参数。如果异常与之匹配且是最先匹配到的,则虚拟机将使用这个catch块来处理异常。
//3、在catch块中可以使用这个块的异常参数来获取异常的相关信息。异常参数是这个catch块中的局部变量,其它块不能访问。
//4、如果当前try块中发生的异常在后续的所有catch中都没捕获到,则先去执行finally,然后到这个函数的外部caller中去匹配异常处理器。
//5、如果try中没有发生异常,则所有的catch块将被忽略。
}catch(Exception exception){
//...
}finally{
//1、finally块通常是可选的。
//2、无论异常是否发生,异常是否匹配被处理,finally都会执行。
//3、一个try至少要有一个catch块,否则, 至少要有1个finally块。但是finally不是用来处理异常的,finally不会捕获异常。
//4、finally主要做一些清理工作,如流的关闭,数据库连接的关闭等。
}
二、常见异常种类
- 算术异常类:ArithmeticExecption
- 空指针异常类:NullPointerException
- 类型强制转换异常:ClassCastException
- 数组负下标异常:NegativeArrayException
- 数组下标越界异常:ArrayIndexOutOfBoundsException
- 违背安全原则异常:SecturityException
- 文件已结束异常:EOFException
- 文件未找到异常:FileNotFoundException
- 字符串转换为数字异常:NumberFormatException
- 操作数据库异常:SQLException
- 输入输出异常:IOException
- 方法未找到异常:NoSuchMethodException
三、throws异常处理
通过throws抛出异常,在被调用出处理。具体实例如下:
//第一种:throws后面接Exception
public static void main(String[] args) {
try {
int result = test();//被调用函数可能发生异常
System.out.println("one和two的商是:" + result);
} catch (ArithmeticException e) {
System.out.println("除数不允许为零");
e.printStackTrace();
}catch(InputMismatchException e){
System.out.println("请输入整数");
e.printStackTrace();
}
}
public static int test() throws Exception{
Scanner input = new Scanner(System.in);
System.out.println("=====运算开始=====");
System.out.print("请输入第一个整数:");
int one = input.nextInt();
System.out.print("请输入第二个整数:");
int two = input.nextInt();
System.out.println("=====运算结束=====");
return one / two;
}
//第二种:throws后面接Exception
public static void main(String[] args) {
try{
int result = test();//被调用函数可能发生异常
System.out.println("one和two的商是:" + result);
}catch(ArithmeticException e){
}catch(InputMismatchException e){
}catch(Exception e){
}
}
/**
* 测试接收数据相除结果的方法
* @return 两个接收数据的商
* @throws ArithmeticException
* @throws InputMismatchException
*/
public static int test() throws ArithmeticException,InputMismatchException{
Scanner input = new Scanner(System.in);
System.out.println("=====运算开始=====");
System.out.print("请输入第一个整数:");
int one = input.nextInt();
System.out.print("请输入第二个整数:");
int two = input.nextInt();
System.out.println("=====运算结束=====");
return one / two;
}