You are on page 1of 11

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.

2. Unchecked exceptions − An unchecked exception is an exception


that occurs at the time of execution. These are also called
as Runtime Exceptions. These include programming bugs, such
as logic errors or improper use of an API. Runtime exceptions
are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to
call the 6th element of the array then
an ArrayIndexOutOfBoundsExceptionexception occurs.
3. Errors − These are not exceptions at all, but problems that
arise beyond the control of the user or the programmer. For
example, if a stack overflow occurs, an error will arise. They
are also ignored at the time of compilation.

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

Examples of Built-in Exception:


● Arithmetic exception
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
    public static void main(String args[])
    {
        try {
            int a = 30, b = 0;
            int c = a/b;  // cannot divide by zero
            System.out.println ("Result = " + c);
        }
        catch(ArithmeticException e) {
            System.out.println ("Can't divide a number by 0");
        } } }
● NullPointer Exception

//Java program to demonstrate NullPointerException


class NullPointer_Demo
{
    public static void main(String args[])
    {
        try {
            String a = null; //null value
            System.out.println(a.charAt(0));
        } catch(NullPointerException e) {
            System.out.println("NullPointerException..");
        }  } }
Output:
NullPointerException..

● StringIndexOutOfBound Exception

// Java program to demonstrate StringIndexOutOfBoundsException

class StringIndexOutOfBound_Demo

{
    public static void main(String args[])

    {

        try {

            String a = "This is like chipping "; // length is 22

            char c = a.charAt(24); // accessing 25th element

            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 {

   public static void main(String args[]) {

        try { // Following file does not exist

            File file = new File("E://file.txt");

  FileReader fr = new FileReader(file);

        } catch (FileNotFoundException e) {

           System.out.println("File does not exist");

        }  } }

Output:
File does not exist
● NumberFormat Exception
// Java program to demonstrate NumberFormatException

class  NumberFormat_Demo

{
    public static void main(String args[])

    {

        try {

            // "akki" is not a number

            int num = Integer.parseInt ("akki") ;

System.out.println(num);

        } catch(NumberFormatException e) {

            System.out.println("Number format exception");

        } }}

Output:
Number format exception
● ArrayIndexOutOfBounds Exception
// Java program to demonstrate ArrayIndexOutOfBoundException

class ArrayIndexOutOfBound_Demo

    public static void main(String args[])

    {  try{

            int a[] = new int[5];

            a[6] = 9; // accessing 7th element in an array of size 5

        }

        catch(ArrayIndexOutOfBoundsException e){

            System.out.println ("Array Index is Out Of Bounds");

        }}}

Output:
Array Index is Out Of Bounds

Java try-catch block


Java try block: Java try block is used to enclose the code that might throw an exception. It
must be used within the method.If an exception occurs at the particular statement of try
block, the rest of the block code will not execute. So, it is recommended not to keeping the
code in try block that will not throw an exception.

Java try block must be followed by either catch or finally block.


Syntax of try-catch block

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.

4. throw :The "throw" keyword is used to throw an exception.

5. throws:The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method. It is always
used with method signature.
Multiple Catch Blocks

A try block can be followed by multiple catch blocks. The syntax


for multiple catch blocks looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block}
The Finally Block
The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-
type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the
following syntax −
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.}
Example
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e)
{ System.out.println("Exception thrown :" + e); }
finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}}}
Output:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

throw and throws


Throw throws

Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.

Checked exception cannot be propagated Checked exception can be propagated with


using throw only. throws.

Throw is followed by an instance. Throws is followed by class.

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

You might also like