“首先我先讲解下异常的工作原理。你可通过下例有个大致了解:”
使用异常的代码:
class ExceptionExampleOriginal
{
public static void main(String[] args)
{
System.out.println("main 方法开始");
try
{
System.out.println("main 调用前");
method1();
System.out.println("main 调用后");
}
catch (RuntimeException e)
{
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main 方法结束");
}
public static void method1()
{
System.out.println("method1 开始");
method2();
System.out.println("method1 结束");
}
public static void method2()
{
System.out.println("method2");
String s = "消息:未知异常";
throw new RuntimeException(s);
}
}
过程的大概表示
public class ExceptionExample
{
private static Exception exception = null;
public static void main(String[] args)
{
System.out.println("main 方法开始");
System.out.println("main 调用前");
method1();
if (exception == null)
{
System.out.println("main 调用后");
}
else if (exception instanceof RuntimeException)
{
RuntimeException e = (RuntimeException) exception; exception = null;
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main 方法结束");
}
public static void method1()
{
System.out.println("method1 开始");
method2();
if (exception != null) return;
System.out.println("method1 结束");
}
public static void method2()
{
System.out.println("method2");
String s = "消息:未知异常";
exception = new RuntimeException(s); return;
}
}
“我完全糊涂了。”
“没关系,让我解释下这个过程。”
“在左侧的示例中,我们依次调用了一些方法。在 method2
中,我们特意创建并抛出一个异常(我们创建了一个错误)。”
“右边的例子显示了正在发生的事情。”
“看看 method2
。我们并不创建异常,而是创建了 RuntimeException
对象,将其保存为 static 变量 exception
,然后使用 return
语句立即退出方法。”
“在 method1
中,调用 method2
后,我们检查是否有异常。如果有异常,则 method1
立即结束。在 Java 中,每个 (!) 方法调用之后,都会间接执行这样的检查。”
“哇!”
“不错。”
“在右列中,我使用 main 方法大致显示了使用 try-catch 结构捕获异常时发生的情况。如果没有异常,那么一切将继续正常运行。如果存在异常,并且与 catch 语句中指定的类型相同,则我们将对其进行处理。”
“ throw
和 instanceof
是什么意思?”
“看看最后一行:throw new RuntimeException(s);
。这是创建和抛出异常的方法。我们暂时不涉及这个。这只是一个例子。”
“我们使用 a instanceof B
检查是否对象 a
是否为 B
类型,即变量异常所引用的对象是否是一个 RuntimeException。这是一个 boolean 表达式。”
“我想我明白了。差不多明白了。”
GO TO FULL VERSION