捕获和抛出异常(Ctrl+Alt+T)
生活随笔
收集整理的這篇文章主要介紹了
捕获和抛出异常(Ctrl+Alt+T)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
捕獲和拋出異常(Ctrl+Alt+T)
-
異常處理五個關鍵字
- try、catch、finally、throw、throws
- package com.exception;public class Test {public static void main(String[] args) {//假如要捕獲多個異常:從小到大! // int a=1; // int b=0; // System.out.println(a/b); // Exception in thread "main" java.lang.ArithmeticException: / by zero // at com.exception.Test.main(Test.java:8) // try {//監控區域 // // System.out.println(a/b); // }catch (ArithmeticException e){//catch(需要捕獲的異常類型) 捕獲異常 // System.out.println("程序出現異常,變量b不能為0"); // }finally {//處理善后工作 // System.out.println("finally"); // } // try {//監控區域 // new Test().b(); // }catch (StackOverflowError e){//catch(需要捕獲的異常類型) 捕獲異常 // System.out.println("StackOverflowError"); // }catch (Exception e){ // System.out.println("Exception "); // }catch (Throwable e){ // System.out.println("Throwable"); // } finally {//處理善后工作 // System.out.println("finally"); // }//輸出StackOverflowError//finally//finally可以不要 假設IO、資源 要關閉try {new Test().test(1,0);} catch (ArithmeticException e) {e.printStackTrace();} finally {}}public void a(){b();}public void b(){a();}//假設這個方法中處理不了這個異常。方法上拋出異常public void test(int a,int b) throws ArithmeticException{if(b==0){ // throw throwsthrow new ArithmeticException();//主動拋出異常;一般在方法中使用}System.out.println(a/b);} } public static void main(String[] args) {int a=1;int b=0;//Ctrl+Alt+Ttry {System.out.println(a/b);} catch (Exception e) {e.printStackTrace();(打印錯誤的棧信息)} finally {} }
總結
以上是生活随笔為你收集整理的捕获和抛出异常(Ctrl+Alt+T)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL数据库查询基础(主讲MySQL,必
- 下一篇: 一个简洁实用的后台管理系统AWESOME