Java教程

Java异常01——捕获和抛出异常

本文主要是介绍Java异常01——捕获和抛出异常,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

捕获和抛出异常

 

异常处理五个关键字

try , catch , finally , throw , throws

try catch finally(快捷键:选中要要监控的代码语句 快捷键: ctrl + alt + t)
 package exception;
 ​
 public class Test {
     public static void main(String[] args) {
         int a = 1;
         int b = 0;
 ​
         try{//try 监控区域
             System.out.println(a/b);
         }catch (ArithmeticException e){//catch 捕获异常
             System.out.println("程序出现异常,b不能为0");
         }finally {// 处理善后工作
             System.out.println("finally");
         }
         
         //finally 可以不要finally, 用: 假设IO,资源需要关闭
         
     }
 }
 ---------------------------------------------------------------------------------------------------
 ​
 // 选中要要监控的代码语句 快捷键: ctrl + alt + t
 package exception;
 ​
 public class Test {
     public static void main(String[] args) {
         int a = 1;
         int b = 0;
         
         // 假设要捕获多个异常: 异常类型:从小到大
         
         try{//try 监控区域
             System.out.println(a/b);
         }catch (Error e){//catch(想要捕获的异常类型!) 捕获异常
             System.out.println("Error");
         }catch (Exception e){
             System.out.println("Exception");
         }catch (Throwable t){
             System.out.println("Throwable");
         }
         finally {// 处理善后工作
             System.out.println("finally");
         }
 ​
         //finally 可以不要finally, 用: 假设IO,资源需要关闭
 ​
     }
 }
 ​
throw throws
 package exception;
 ​
 public class Test {
     public static void main(String[] args) {
 ​
         new Test().test(1,0);
     }
     
     public void test(int a , int b){
         if(b==0){// throw  throws
             throw new ArithmeticException();//主动抛出异常,一般在方法中使用  throw
         }
         System.out.println(a/b);
     }
 }
 ---------------------
     package exception;
 ​
 public class Test {
     public static void main(String[] args) {
 ​
         try {
             new Test().test(1,0); // try  catch
         } catch (ArithmeticException e) {
             e.printStackTrace();
         }
     }
     
     // 假设这个方法中,处理不了这个异常。方法上抛出异常
     public void test(int a , int b) throws ArithmeticException{ // throws
         if(b==0){// throw  throws
             throw new ArithmeticException();//主动抛出异常,一般在方法中使用
         }
         System.out.println(a/b);
     }
 }

学习内容源自视频:b站狂神说Java

这篇关于Java异常01——捕获和抛出异常的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!