0
点赞
收藏
分享

微信扫一扫

Java抛出和捕获异常

guanguans 2022-04-13 阅读 84
java

抛出和捕获异常

  • 抛出异常

  • 捕获异常

  • 异常处理的五个关键字

    • try、catch、finally、throw、throws

try{}catch{}finally{}

  • try、catch、finally三个关键字是一起使用的。

  • 快捷键:Ctrl + Alt + T

  • 语法格式:

 try{ // 监控区域

           //  可能存在异常的代码

      }catch{ // 捕获异常

           //  捕获异常后进行的操作

      }finally{ // 善后操作  也可以不要finally

           // 善后所做的操作

      }
  • Code:
public class Demo_01 { 
	public static void main(String[] args) {

        int a = 10;
 		int b = 0; 
 		 
       	 try {
           	 System.out.println(a/b);
       	 } catch (ArithmeticException e) {
             System.out.println("0不能做被除数。");
             e.printStackTrace();
       	 } finally {
           	 System.out.println("finally");
       	 }
   	 }
}

在这里插入图片描述

  • try{} catch{} finally{} 可以捕获多个异常。
		try {
    	    System.out.println(a/b);
 		} catch (Exception exception) {
            System.out.println("0不能做被除数。");
            exception.printStackTrace();
        }catch (Error error){
            error.printStackTrace();
        }catch (Throwable throwable){ // 最大的异常只能放到最后,不能放到前面
            throwable.printStackTrace();
        }finally {
            System.out.println("finally");
        }

throw

  • throw 在方法内主动抛出异常
public  void test(int a , int b){

    if (b == 0){
         throw new ArithmeticException();// 主动抛出异常
   	}
    
     System.out.println(a/b);
}
// main方法
public static void main(String[] args) {

        new Demo_02().test(10,0);
 }

在这里插入图片描述

throws

  • throws 在方法上抛出异常
public class Demo_03{
	// 假设方法内处理不了这个异常,方法抛出异常。
    public void test(int a , int b)throws ArithmeticException{ 

        System.out.println(a/b);
    }

    public static void main(String[] args) {

        new Demo_03().test(10,0);
    }
}
举报

相关推荐

0 条评论