异常 try cath finally

知识点

1.try

	try{}//捕捉异常用来检测在try块中的代码是否有异常,和catch连用

2.catch

	catch(异常类型){}// try捕捉到异常时才会执行代码块,作用:将捕捉的异常进行处理  和try连用

3.finally

	finally{}//无论有没有异常都执行的代码块,一般用来释放资源

4.throws

	一般出现在函数后面,抛出可能出现的异常

5.throw

	抛出一个异常

实例说明:

1. try catch finally

当没有try catch时
	 public static void main(String[] age) {
  		int a = 2/0 ;
  		System.out.println("计算成功"); 
  		}

可以看出,JVM直接输出红字异常信息并且出现异常之后程序(代码)直接被终止,没有执行后面的输出语句,在这里插入图片描述

使用try catch 对异常进行处理
 public static void main(String[] age) {
  try{//检测是否有异常
      int a=2/0;
  }catch (ArithmeticException e){//对错误信息进行处理
      System.out.println("被除数不能为0");
  }finally {
      System.out.println("我是finally我被执行了");
  }
  System.out.println("计算成功");
}

在这里问我们将异常处理(输出异常信息)后,出现异常之后的代码仍然执行出来了,
在这里插入图片描述

finally作用
	 public static void main(String[] age) {
  try{//检测是否有异常
      int a=2/1;
  }catch (ArithmeticException e){//对错误信息进行处理
      System.out.println("被除数不能为0");
  }finally {
      System.out.println("我是finally我被执行了");
  }
  System.out.println("计算成功");
}

本段代码,可以看出并没有捕捉到异常finally被执行了,可以看看上一个例子捕捉到异常finally也被执行了,由此可以得出结论:无论异常有没有异常被捕捉finally都执行
在这里插入图片描述

throw throws
 public static void main(String[] age)throws ArithmeticException{
        System.out.println(f(20,0));
    }
    public  static  float  f(float a , float b){
        if(b==0){ //如果数据不符合要求就抛出一个异常
            throw new ArithmeticException("被除数不能为0");
        }
        return a/b;
    }
   当数据不符合要求时  throw抛出了一个异常,给调用者,输出函数没有对异常处理的机制又将这个异常抛给main,mian接收到异常,通过theows将异常抛给了jvm,然后就红字输出显示异常信息

在这里插入图片描述
博文仅个人理解,欢迎大佬指正!!

发布了45 篇原创文章 · 获赞 47 · 访问量 1729

猜你喜欢

转载自blog.csdn.net/qq_44784185/article/details/102853890