「Java 11」例外(Exception)クラスを継承して独自の例外クラスを作成する

環境
JavaSE 11
Spring Tool Suite 4

書式
public class 独自の例外クラス名 extends Exception
Exceptionクラスを継承します。
Exceptionクラスとそのサブクラスは、通常のアプリケーションでキャッチされる可能性のある状態を示すThrowableの形式の1つです。
独自の例外クラスを作成する場合、既存の例外クラスを継承する必要があります。

使用例
1.独自の例外クラスを定義します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Exceptionクラスを継承
pulic class TestException extends Exception {
private static final long serialVersionUID = 1L;
//コンストラクタ 引数なし
public TestException() {
super();
}
// コンストラクタ 引数str
public TestException(String msg){
super(msg) ;
}
// コンストラクタ 引数str
public TestException(String msg, Throwable e) {
super(msg,e) ;
}
}
// Exceptionクラスを継承 pulic class TestException extends Exception { private static final long serialVersionUID = 1L; //コンストラクタ 引数なし public TestException() { super(); } // コンストラクタ 引数str public TestException(String msg){ super(msg) ; } // コンストラクタ 引数str public TestException(String msg, Throwable e) { super(msg,e) ; } }
// Exceptionクラスを継承
pulic class TestException extends Exception {

  private static final long serialVersionUID = 1L;
  
  //コンストラクタ 引数なし
  public TestException() {
    super();
   }
  // コンストラクタ 引数str
  public TestException(String msg){
    super(msg) ; 
  }
  // コンストラクタ 引数str
  public TestException(String msg, Throwable e) {
    super(msg,e) ;
  }

}

2.独自の例外クラスを使用します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@RequestMapping(value = {"/copy"})
public String execute() throws Exception{
try {
処理コード
}catch(TestException e)
super.addError(e.getMessage());
return "user/copy";
}
@RequestMapping(value = {"/copy"}) public String execute() throws Exception{ try { 処理コード }catch(TestException e) super.addError(e.getMessage()); return "user/copy"; }
@RequestMapping(value = {"/copy"})
public String execute() throws Exception{

  try {
   処理コード
  }catch(TestException e)
   super.addError(e.getMessage());
  
  return "user/copy"; 
}

 

Java

Posted by arkgame