Exceptions in Java
Exceptions in Java
What is Exception
• Exception is an unexpected event that occurs during the execution of a
program
• Exceptions are run time errors
• The process of handling the exceptions is known as Exception Handling.
• In java the following keywords are used to handle exceptions
1. try
2. catch
3. throw
4. throws
5. finally
Try-catch block
• The set of statements that may generate an exception are enclosed in a block known as try block.
• The try block contains a set of statements where an exception can occur.
• In order to handle those exceptions which get raised in the try block, we use the catch block.
• A catch block is where you handle the exceptions, i.e., the catch block specifies what is to be done when
an exception occurs.
Syntax:
try
{
// statements that may cause an exception
}
catch (exceptionType e)
{
// error handling code
}
Try-catch block…
Example
Multiple catch blocks…
try{
//code
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println(" Exception occurs");
}
finally block
• A finally block contains all the crucial statements that must be executed irrespective of whether an exception occurs or not.
• The statements present in this block will always execute regardless of whether an exception occurs in a try block or not.
finally block is optional and can be used only with a try-catch block.
Syntax:
try{
//Statements that may cause an exception
}
catch (ExceptionType e) {
//Error handling code
}
finally {
//Statements that must be executed
}
Types of Exceptions
• There are two different types of exceptions in Java:
• Checked Exception
• Unchecked Exception
• Checked Exception
• All exceptions other than runtime exceptions are known as Checked Exceptions as the compiler checks them during
compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the
program, you will get a compilation error. In this case, the programmers are forced to either handle these exceptions or
declare to allow their propagation.
• E.g. - SQLException, IOException, etc. are Checked Exceptions
• Unchecked Exception
• Unchecked exceptions are runtime exceptions. These exceptions are not checked at compile-time. So, the compiler does
not check whether the programmer has handled them or not. In this case, the programmers are not forced to handle or
declare their propagation.
• E.g. - ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. are Unchecked Exceptions
Exception Hierarchy
• The hierarchy of the exception classes is shown in the below diagram.
• All the exceptions inherit the Exception class, which is a child of the Throwable class.
throw
• In Java, we can define our own set of conditions or rules and throw an exception explicitly using throw keyword.
Syntax:
Syntax: