Exception Handling in Java
Exception Handling in Java
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
● A user has entered an invalid data.
● A file that needs to be opened cannot be found.
● Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
● Based on these, we have three categories of Exceptions
1. Checked exceptions − A checked exception is an exception that is
checked (notified) by the compiler at compilation-time,
these are also called as compile time exceptions.
For example, if you use FileReader class in your program to read data from a file, if
the file specified in its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler prompts the programmer to handle
the exception.
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class.
The Exception class has two main subclasses: IOException class and RuntimeException
Class.
Types of Exception in Java
Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions.
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index
is either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the
size of the string
● StringIndexOutOfBound Exception
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
} }}
Output:
StringIndexOutOfBoundsException
● FileNotFound Exception
//Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
} } }
Output:
File does not exist
● NumberFormat Exception
// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
System.out.println(num);
} catch(NumberFormatException e) {
} }}
Output:
Number format exception
● ArrayIndexOutOfBounds Exception
// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{ try{
}
catch(ArrayIndexOutOfBoundsException e){
}}}
Output:
Array Index is Out Of Bounds
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Java catch block: Java catch block is used to handle the Exception by declaring the type of
exception within the parameter.The catch block must be used after the try block only. You
can use multiple catch block with a single try block.
Eg:
public class TryCatchExample {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} }
Eg:
public class TryCatchExample {
public static void main(String[] args) {
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e); }
System.out.println("rest of the code");
} }
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
1. try: The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't use
try block alone.
2. 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.
3. finally:The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method() throws IOException,
SQLException
Java throw: The throw keyword in Java is used to explicitly throw an exception from a method
or any block of code. We can throw either checked or unchecked exception. The throw keyword
is mainly used to throw custom exceptions.
Example: throw new ArithmeticException("/ by zero");
But this exception i.e, Instance must be of type Throwable or a subclass of Throwable..The
flow of execution of the program stops immediately after the throw statement is executed and the
nearest enclosing try block is checked to see if it has a catch statement that matches the type of
exception. If it finds a match, controlled is transferred to that statement otherwise next
enclosing try block is checked and so on. If no matching catch is found then the default
exception handler will halt the program.
Example
import java.io.*;
class ExceptionThrow
{
public static void main(String args[])
{
int x;
try{
x=10/0;
throw new ArithmeticException(); }
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
//System.out.println(e);
} }}
Throws in try-catch mechanism
throws is a keyword in Java which is used in the signature of method to indicate that this method
might throw one of the listed type exceptions. The caller to these methods has to handle the
exception using a try-catch block.
Syntax
type method-name(parameter list)throws exception-list
{
//body of method
}
exception_list is a comma separated list of all the exceptions which a method might throw.
Example
import java.io.*;
class ExceptionThrows
{ public static void main(String args[])throws Exception
{ int x;
try{
Scanner in=new Scanner(System.in);
String str;
System.out.println("enter value of x");
str=in.nextLine();
System.out.println(" value of x="+str);
}
catch(Exception e)
{
}}}
Nested Try example
import java.io.*;
class NestedTry
{ public static void main(String args[])
{ try{
int a=args.length;
int b=12/a;
System.out.println("a="+a);
if(a==1)
a=a/(a-a);
try
{
//nested tryblock
if(a==2){
int c[]={1};
c[a]=99;
}}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());}
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}}}
Creating our own exception
1. You can create your own exceptions in Java.
2. All exceptions must be a child of Throwable.
3. If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
4. If you want to write a runtime exception, you need to extend the RuntimeException class.
class MyException extends Exception {
}
You just need to extend the predefined Exception class to create your own Exception.
class MyException extends Exception{
int a;
MyException(int b) {
a=b; }
public String toString(){
return ("Exception Number = "+a) ;
}}
class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}}}
Example2
class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
} }
// A Class that uses above MyException
public class Main
{
// Driver Program
public static void main(String args[])
{ try
{
// Throw an object of user defined exception
throw new MyException("Welcome");
}
catch (MyException e)
{
System.out.println("Caught");
// Print the message from MyException object
System.out.println(e.getMessage());
}}}
Output
Caught
Welcome