異常處理
自定義異常基礎類
package com.cloud.exception;
/**
* 構建一個基礎的異常類
*/
public class DefineException extends RuntimeException{
//VersionUID
private static final long serialVersionUID = 3042686055658047285L;
//錯誤位置
protected String positionName;
//錯誤標籤
protected String errorLabel;
//錯誤信息
protected String message = "";
public String getMessage(){
return message;
}
//封裝屬性
public void setNameAndMessage(String errorLabel,String message){
this.errorLabel = errorLabel;
this.message = message;
}
public void setPositionName(String positionName) {
this.positionName = positionName;
}
public void setErrorLabel(String errorLabel) {
this.errorLabel = errorLabel;
}
public void setMessage(String message) {
this.message = message;
}
public String getErrorLabel(){
return this.errorLabel;
}
public String getPositionName(){
return this.positionName;
}
//參照Throwable源碼的幾個構造方法
public DefineException(){
super();
}
public DefineException(Throwable throwable){
super(throwable);
}
public DefineException(String errorLabel){
super(errorLabel);
this.errorLabel = errorLabel;
this.message = errorLabel;
}
public DefineException(String positionName,String errorLabel){
super(errorLabel);
this.errorLabel = errorLabel;
this.positionName = positionName;
this.message = errorLabel;
}
public DefineException(String positionName,Throwable throwable){
super(throwable);
this.positionName = positionName;
}
public DefineException(String positionName,String errorName,Throwable throwable){
super(throwable);
this.errorLabel = errorName;
this.positionName = positionName;
this.message = errorName;
}
}
擴展異常類
package com.cloud.exception;
/**
* 擴展一個自己使用的異常類
*/
public class MyException extends DefineException{
private static final long serialVersionUID = -3042686055658047285L;
public MyException(){}
public MyException(Throwable throwable){
super(throwable);
}
public MyException(String positionName,String errorLabel){
super(positionName, errorLabel);
}
public MyException(String errorLabel){
super(errorLabel);
}
public MyException(String positionName,Throwable throwable){
super(positionName, throwable);
}
public MyException(String positionName,String errorLabel,Throwable throwable){
super(positionName, errorLabel, throwable);
}
}
異常處理原則
package com.cloud.Test;
import com.cloud.exception.MyException;
/**
* 異常處理原則:
* 1.如果不能處理異常,不要捕獲該異常。
* 2.如果要捕獲,應在離異常源近的地方捕獲它。
* 3.不要捕獲的異常,但是什麼也不處理。
*/
public class Test4 {
public static void main(String[] args) {
MyExe mx = new MyExe();
try {
/*這裏發生異常,則直接離開try代碼進入catch*/
//int i = 1/0;
/*這個方法執行扔出的異常就不會被捕獲*/
mx.getI();
}catch(MyException mp){
String info = mp.getMessage();
System.out.println("捕獲自定義異常"+info);
} catch (Exception e) {
e.printStackTrace();
System.out.println("捕獲Exception異常");
}
}
}
class MyExe{
public void getI(){
MyException me = new MyException();
try {
int te = 2/0;
} catch (MyException e) {
me.setMessage("除數不能爲0!");
throw me;
}catch (Exception e) {
System.out.println("Exception異常");
e.printStackTrace();
}
}
}