"I'd like to tell you a bit about how exceptions work. The example below should give you a rough idea of what happens:"
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;
}
}
"I'm totally lost."
"All right. Let me explain what's going on."
"In the example on the left, we call a few methods in succession. In method2
, we deliberately create and throw an exception (we create an error)."
"The example on the right shows what is happening."
"Look at method2
. Instead of creating an exception, we create a RuntimeException
object, save it to the static variable exception
, and then immediately exit the method using a return
statement."
"In method1
, after calling method2
, we check whether there is an exception. If there is an exception, then method1
ends at once. A check like this is performed indirectly after every (!) method call in Java."
"Wow!"
"Wow is right."
"In the right column, I've used the main method to show approximately what happens when an exception is caught using a try-catch construct. If there is no exception, then everything continues running as expected. If there is an exception and it is the same type specified in the catch statement, then we handle it."
"What do throw
and instanceof
mean ?"
"Look at the last line: throw new RuntimeException(s);
. This is how you create and throw an exception. We won't work on that yet. It was just an example."
"We use a instanceof B
to check whether object a
is of type B
, i.e. whether the object referenced by the variable exception is a RuntimeException. This is a boolean expression."
"I think I got it. Almost."
GO TO FULL VERSION