Java學習筆記----異常
這是從別的網站盜來的圖。異常分為兩種:Error:這是程式無法處理的錯誤Exception:這是異常,又分為兩種: 處理異常的方法:拋出異常:throws 舉個例子,汽車出現故障了,汽車自己沒辦法處理,就只能交給人去處理throw出現在函數體裡面,這個算是自訂了一個自己的異常類。可以輸出自己所定義的異常。注意:這個throw也是需要throws MyException的。一開始我以為不用。所以出錯了代碼:
package com.ehealth.exc;import java.lang.Exception;public class ExcTest { static int question(int x,int y) throws MyException{ if(y<0){ throw new MyException("除數不能是負數"); } return x/y; } static int que(int x,int y ) throws MyException{ if(x<0){ throw new MyException("第一個數字不能小於0"); } return x+y; } public static void main(String[] args) { // TODO Auto-generated method stub int x=3; int y=-1; int i=-1; int j=1; try { int a=que(i,j); } catch (MyException e1) { // TODO Auto-generated catch block System.out.println(e1.getMessage()); } try{ int res=question(x,y); }catch(MyException e){ System.out.println(e.getMessage()); }catch(ArithmeticException e){ System.out.println(e.getMessage()); }catch(Exception e){ System.out.println("程式發生了其他的異常!"); } }}class MyException extends Exception{ String message; public MyException(String Err){ message=Err; } public String getMessage(){ return message; }}