Javaでカスタム例外をスローする方法は何ですか?
Javaでは、独自の例外型を定義し、必要な時にその例外をスローするためにカスタム例外クラスを記述することができます。以下は簡単な例です:
// 自定义异常类
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
// 抛出自定义异常
public class Main {
public static void main(String[] args) {
try {
throw new MyCustomException("这是我自定义的异常");
} catch (MyCustomException e) {
System.out.println("捕获到自定义异常:" + e.getMessage());
}
}
}
上記の例では、Exceptionクラスを継承したMyCustomExceptionというカスタム例外クラスを作成し、コンストラクターで例外情報を渡しています。その後、Mainクラスでthrow new MyCustomException(“これは私が定義した例外です”)という文を使用してカスタム例外をスローし、最後にcatchブロックでその例外をキャッチして処理します。