RunnableインターフェイスやThreadクラスを実装する場合、run()メソッドがオーバーライドされている限り、例外を発生させることはできません。
run()メソッドで直接、例外をキャッチオフして処理します。
public class ExceptionHandling {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
int count = 0;
while (true) {
++count;
System.out.println("私は、"+ count + "次回 "である。);
if (count == 5) {
throw new RuntimeException();
}
}
} catch (RuntimeException e) {
System.out.println("例外が処理される");
}
}
});
thread.start();
}
}
タイマーカウントを使用し、ループが5回に達したときにRuntimeExceptionを投げ、そしてcatchに例外を処理させます。そうすると、何かがうまくいかず、例外を処理し、相手側は例外があることは知っているが、それを処理することができない、これはよくない、だから、より良い方法はありますか?
普通のメソッドを書いて、例外を投げて、呼び出し元に自分のスレッドを作らせましょう。
public class ExceptionHandling implements Runnable{
public static void main(String[] args) {
ExceptionHandling exceptionHandling = new ExceptionHandling();
Thread thread = new Thread(exceptionHandling);
thread.start();
}
public void generalMethod() throws RuntimeException{
int count = 0;
while (true) {
++count;
System.out.println("私は、"+ count + "次回 "である。);
if (count == 5) {
throw new RuntimeException();
}
}
}
@Override
public void run() {
try {
generalMethod();
}catch (RuntimeException e){
System.out.println("呼び出し側のメソッドがスローした例外を処理する");
}
}
}