Exception Handling in Java
Exception Handling in Java
Exception handling is one of the most important feature of java programming that
allows us to handle the runtime errors caused by exceptions.
What is an Exception?
An Exception is an unwanted event that interrupts the normal flow of the program.
When an exception occurs program execution gets terminated. In such cases we get
a system generated error message. The good thing about exceptions is that they can
be handled in Java. By handling the exceptions we can provide a meaningful
message to the user about the issue rather than a system generated message, which
may not be understandable to a user.
Exception Handling
If an exception occurs, which has not been handled by programmer then program
execution gets terminated and a system generated error message is shown to the
user. Exception handling ensures that the flow of the program doesn’t break when
an exception occurs.
Try block
The try block contains set of statements where an exception can occur. A try block
is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must be followed by catch blocks or finally block
or both.
}
Catch block
A catch block is where you handle the exceptions, this block must follow the try
block. A single try block can have several catch blocks associated with it. You can
catch different exceptions in different catch blocks. When an exception occurs in
try block, the corresponding catch block that handles that particular exception
executes. For example if an arithmetic exception occurs in try block then the
statements enclosed in catch block for arithmetic exception executes.
class Division {
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e)
finally {