Introduction
What is Exception in Java?
In Java, an exception is an event that disrupts the normal flow of the program.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors.
- Advantage of Exception Handling: The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.
Object class stands at the root of the Hierarchy. Throwable is the subclass of object class and serves as a superclass for Errors and Exception classes.
Types of Exceptions
There are two types of exception,
2) Unchecked Exceptions: These are runtime exceptions caught by the java runtime system. It is not compulsory to handle unchecked exceptions. As they are anyway handled by JVM. Ex: ArithmeticException, NullPointerException, ArrayStoreException etc.
Exception Handling Keywords
There are 5 keywords in Java Exception Handling.
- try: The statements susceptible to a runtime error fall under the try block. A try block can’t exist independently. It has to accompany by either catch or finally block.
- catch: The catch block contains the statements of action to be taken when an exception occurs in the try block. Catch used without a try block leads to a compile-time error.
- finally: This block contains a set of statements that executes whether or not an exception is thrown.
- throw: The throw keyword utilizes to throw the exception explicitly.
- throws: This keyword is used with the method prototype which indicates the type of exceptions that the method might throw to the java runtime.
Syntax of Java Exception Handling
try
{
//code to be monitored for an exception
}
catch(exception_object)
{
//exception handler for catching the exception_object
}
finally
{
//The code will get executed in any case
}
Example:
class Test{
public static void main(String[] args) {
int a= 32;
int result;
try
{
result = a/0;
System.out.println("Result of division: " +result);
}
catch (ArithmeticException e)
{
System.out.println("The Exception is: " +e );
}
}
}
Post a Comment
0 Comments