Exception Handling
One of the most important features of java programming is exception handling, which allows us to handle runtime errors caused by exceptions. We will learn what an exception is, the different sorts of exceptions, exception classes, and how to manage exceptions in Java using examples
What is an exception ?
An exception is an unintended event that interrupts the program's normal flow. When a programs detects an exception, it is terminated. In such cases, we receive an error message generated by the system. Exceptions are useful because they can be handled in Java. We may provide a meaningful message to the user about the issue instead of a system produced message, which may not be clear to a user, by managing exceptions.
exception handling in java |
Why an exception occurs ?
There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, bad input data provided by user etc.
Why use Exception handling?
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.
Error vs exception :
Error : indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error.
Exception :are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions.
Hierarchy of Java Exception classes :
Hierarchy of Java Exception classes |
Types of exceptions :
1. Checked Exceptions :
2. Unchecked Exceptions :
Java Exception Keywords :
try :
- 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 :
- The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
finally :
- A finally block contains all the crucial statements that must be executed whether exception occurs or not. The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc.
throw :
- The "throw" keyword is used to throw an exception.
throws :
- unchecked exception (Runtime) doesn’t get checked during compilation. Throws keyword is used for handling checked exceptions . By using throws we can declare multiple exceptions in one go.
Exception Handling Example :
class Test
{
public static void main(String args[])
{
int num1, num2;
try {
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e)
{
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch (Exception e)
{
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I am out of try-catch block in Java.");
}
}
Output :
You should not divide a number by zero
I am out of try-catch block in Java.
frequently used exceptions :
Arithmetic exception:
class ExampleClass
{
public static void main(String args[])
{
try
{
int a = 30, b = 0;
int output = a / b;
System.out.println("Result: " + output);
}
catch (ArithmeticException e)
{
System.out.println("You Should not divide a number by zero");
}
}
}
Output :
You Should not divide a number by zero
NullPointer Exception :
class Test
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}
catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}
Output :
NullPointerException..
NumberFormatException :
class Test
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("ABC") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}
Output :
Number format exception occurred
ArrayIndexOutOfBoundsException :
class Test
{
public static void main(String args[])
{
try{
int arr[]=new int[10];
//Array has only 10 elements
arr[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Output :
ArrayIndexOutOfBounds
StringIndexOutOfBound :
class Test
{
public static void main(String args[])
{
try{
String str="abcd";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output :
4
StringIndexOutOfBoundsException!!