Java异常No.10

                                       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主要做一些清理工作,如流的关闭,数据库连接的关闭等。 
}

二、常见异常种类

  1. 算术异常类:ArithmeticExecption
  2. 空指针异常类:NullPointerException
  3. 类型强制转换异常:ClassCastException
  4. 数组负下标异常:NegativeArrayException
  5. 数组下标越界异常:ArrayIndexOutOfBoundsException
  6. 违背安全原则异常:SecturityException
  7. 文件已结束异常:EOFException
  8. 文件未找到异常:FileNotFoundException
  9. 字符串转换为数字异常:NumberFormatException
  10. 操作数据库异常:SQLException
  11. 输入输出异常:IOException
  12. 方法未找到异常: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;
}








 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值