Java Reference
In-Depth Information
And suppose the following is a
catch
block immediately following the
try
block:
catch
(Exception e)
{
System.out.println(e.getMessage());
System.out.println("Program aborted.");
System.exit(0);
}
In this case, the method call
e.getMessage()
returns the string
"Input must be positive."
Exception Classes
There are more exception classes than just the single class
Exception
. There are more
exception classes in the standard Java libraries and you can define your own exception
classes. All the exception classes in the Java libraries have—and the exception classes
you define should have—the following properties:
1. There is a constructor that takes a single argument of type
String
.
2. The class has an accessor method
getMessage()
that can recover the string given as
an argument to the constructor when the exception object was created.
try-throw-catch
When used together, the
try
,
throw
, and
catch
statements are the basic mechanism for
throwing and catching exceptions. The
throw
statement throws the exception. The
catch
block catches the exception. The
throw
statement is normally included in a
try
block. When
the exception is thrown, the
try
block ends and then the code in the
catch
block is executed.
After the
catch
block is completed, the code after the
catch
block(s) is executed (provided the
catch
block has not ended the program or performed some other special action).
If no exception is thrown in the
try
block, then after the
try
block is completed, program
execution continues with the code after the
catch
block(s). (In other words, if no exception is
thrown, the
catch
block(s) are ignored.)
SYNTAX
try
{
Some_Statements
<
Either a throw statement or
a method invocation that might throw an exception
or other statement that might throw an exception.
>
Some_More_Statements
}