Java Exception Handling
Java Exception Handling
java.lang.ArithmeticException: / by zero
Exception Handling
"An exception was thrown" is the proper java terminology for "an error happened."
Output:
Throwable
Exception Error
Runtime Exception
Exception Handling
Exception class is used for exceptional conditions that user programs should catch.
Exception of type runtimeexception are automatically defined for the programs that you write.
Error class defines exceptions that are not expected to be caught under normal circumstances.
Uncaught Exceptions
When java runtime system detects an exception
It throws this exception.
Once thrown it must be caught by an exception handler and dealt with immediately.
If exception handling code is not written in the program , default handler of java catch the exception.
The default handler displays a string describing the exception & terminates the program.
Handling exceptions by ourselves provides 2 benefits.
• First it allows you to fix the error.
• Second it prevents the program from automatically terminating.
Exception Handling
Use a try-catch block to handle exceptions that are thrown
try {
// code that might throw exception
If not caught, method must specify If not caught, method may specify
it to be thrown it to be thrown
For errors that the programmer For errors that the programmer
cannot directly prevent from can directly prevent from
occurring occurring,
IOException, NullPointerException,
FileNotFoundException, IllegalArgumentException,
SocketException IllegalStateException
Keyword Summary