Java-异常02 捕获和抛出异常
生活随笔
收集整理的這篇文章主要介紹了
Java-异常02 捕获和抛出异常
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ArithmeticException 算術異常
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){System.out.println("程序出現異常,變量B不能為0");} finally { // 處理善后工作,無論是否有異常,最后都會執行System.out.println("finally");}// finally 可以不寫, 有些 IO,資源 必須要關閉的,可以用finally} }可以寫多個catch,但是只能捕獲一個
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){System.out.println("Error");} catch (Exception e){System.out.println("Exception");} catch (Throwable t){System.out.println("Throwable");} finally { // 處理善后工作,無論是否有異常,最后都會執行System.out.println("finally");}// finally 可以不寫, 有些 IO,資源 必須要關閉的,可以用finally} }可以寫多個catch,但是只能捕獲一個catch。捕獲的順序必須按從小到大來寫
idea 快捷鍵,生成 try catch
throw、throws
public class Test {public static void main(String[] args) {try {new Test().test(1,0);} catch (Exception e) {e.printStackTrace();}System.out.println("0000000");}// 假設這個方法中,處理不了這個異常,方法上拋出異常public void test(int a, int b) throws ArithmeticException{if (b==0){throw new ArithmeticException(); // 主動拋出異常,一般在方法中使用}} }throw: 在方法體中主動拋出異常
throws :在方法上拋出異常
https://www.bilibili.com/video/BV12J41137hu?p=78&spm_id_from=pageDriver
總結
以上是生活随笔為你收集整理的Java-异常02 捕获和抛出异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL server2017和ssms管
- 下一篇: android studio打包纯H5项