「例外がどのように機能するかについて少し説明したいと思います。以下の例は、何が起こるかを大まかに理解できるはずです。」
class ExceptionExampleOriginal
{
public static void main(String[] args)
{
System.out.println("main begin");
try
{
System.out.println("main before call");
method1();
System.out.println("main after call");
}
catch (RuntimeException e)
{
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main end");
}
public static void method1()
{
System.out.println("method1 begin");
method2();
System.out.println("method1 end");
}
public static void method2()
{
System.out.println("method2");
String s = "Message: Unknown Exception";
throw new RuntimeException(s);
}
}
public class ExceptionExample
{
private static Exception exception = null;
public static void main(String[] args)
{
System.out.println("main begin");
System.out.println("main before call");
method1();
if (exception == null)
{
System.out.println("main after call");
}
else if (exception instanceof RuntimeException)
{
RuntimeException e = (RuntimeException) exception; exception = null;
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main end");
}
public static void method1()
{
System.out.println("method1 begin");
method2();
if (exception != null) return;
System.out.println("method1 end");
}
public static void method2()
{
System.out.println("method2");
String s = "Message: Unknown Exception";
exception = new RuntimeException(s); return;
}
}
「完全に迷ってしまいました。」
「わかりました。何が起こっているのか説明しましょう。」
「左側の例では、いくつかのメソッドを連続して呼び出しています。 ではmethod2
、意図的に例外を作成してスローしています (エラーを作成しています)。」
「右の例は何が起こっているかを示しています。」
「見てくださいmethod2
。例外を作成する代わりに、オブジェクトを作成しRuntimeException
、それを静的変数 に保存しexception
、ステートメントを使用してメソッドをすぐに終了しますreturn
。」
「 ではmethod1
、 を呼び出した後method2
、例外があるかどうかをチェックします。例外がある場合は、method1
すぐに終了します。このようなチェックは、Java のすべての (!) メソッド呼び出しの後に間接的に実行されます。」
"おお!"
「わあ、そうですよ。」
「右側の列では、try-catch コンストラクトを使用して例外がキャッチされたときに何が起こるかを示すために main メソッドを使用しています。例外がなければ、すべてが期待どおりに実行され続けます。例外があり、 catch ステートメントで指定された型と同じである場合は、それを処理します。」
「どういう throw
意味 instanceof
ですか?」
「最後の行を見てください: throw new RuntimeException(s);
。これが例外を作成してスローする方法です。これについてはまだ作業しません。これは単なる例です。」
a instanceof B
「オブジェクトa
の型が であるかどうかB
、つまり変数例外によって参照されるオブジェクトが RuntimeException であるかどうかを確認するために使用します。これはブール式です。」
「ほぼわかったと思います。」
GO TO FULL VERSION