java基礎-自定義異常

在軟件開發過程當中,咱們可能須要自定義一些異常來描述一個程序中異常的信息,並以此來區分其餘的異常信息,這樣,咱們就須要自定義一些異常信息。java

那如何實現自定義異常呢?spa

  1. 經過了解,類java.lang.Throwable是全部異常類的基類,它包括兩直接已知子類:Exception和Error,Exception類用於描述程序可以捕獲的異常,如ClassNotFoundException,IOException等。Error類用於指示合理的應用程序不該該試圖捕獲的嚴重問題,如虛擬機錯誤VirtualMachineError,io異常 IOError 等  設計

  2. 自定義異常類能夠繼承Throwable類或者Exception,而不要繼承Error類。自定義異常類之間也能夠有繼承關係,
    須要爲自定義異常類設計構造方法,以方便構造自定義異常對象。
    code

代碼示例:對象

   ArgsException.java繼承

package net.test.test;
public class ArgsException extends Exception {
 //繼承Exception實現自定義異常
 private static final long serialVersionUID = 1L;
 public ArgsException(String msg) {
  super(msg);
 }
 public ArgsException(String msg, Throwable cause) {
  super(msg, cause);
 }
 public ArgsException(Throwable cause) {
  super(cause);
 }
}

  Args2Exception.java開發

package net.test.test;
public class Args2Exception extends Throwable{
 //繼承Throwable基類實現自定義異常
 private static final long serialVersionUID = 1L;
 public Args2Exception(String msg) {
  super(msg);
 }
 public Args2Exception(String msg, Throwable cause) {
  super(msg, cause);
 }
 public Args2Exception(Throwable cause) {
  super(cause);
 }
}

  TestException.java虛擬機

package net.test.test;
public class TestException {
 
 public void e() throws ArgsException{
  //繼承Exception實現自定義異常
  throw new ArgsException("這是一個自定義異常1");
 }
 
 public void t() throws Args2Exception{
  //繼承Throwable基類實現自定義異常
  throw new Args2Exception("這是一個自定義異常2");
 }
 
 public static void main(String[] args) {
  try { 
   new TestException().e();
  } catch (ArgsException e) {
   e.printStackTrace();
  }
  
  try {
   new TestException().t();
  } catch (Args2Exception e) {
   e.printStackTrace();
  }
 }
}

 

運行結果:io

  net.test.test.ArgsException: 這是一個自定義異常1
 at net.test.test.TestException.e(TestException.java:6)
 at net.test.test.TestException.main(TestException.java:19)
net.test.test.Args2Exception: 這是一個自定義異常2
 at net.test.test.TestException.t(TestException.java:10)
 at net.test.test.TestException.main(TestException.java:25)
Exception in thread "main" net.test.test.ArgsError: 這是一個自定義異常3
 at net.test.test.TestException.error(TestException.java:14)
 at net.test.test.TestException.main(TestException.java:30)
相關文章
相關標籤/搜索