Exceptions in Java | Exception Handling in Java | Java Exceptions

Exception:

An exception is an error in the program, which if handled properly the program can continue instead of terminating. By definition, an exception is a condition that is caused by a run-time error in the program.

An exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program. Abnormality does occur when your program is running. For example, you might expect the user to enter an integer, but receive a text string; or an unexpected I/O error pops up at runtime.

If these exceptions are not handled properly, the program terminates abruptly and may cause severe consequences. For example, the network connections, database connections and files may remain opened; database and file records may be left in an inconsistent state.

Any computer application can terminate at any stage of its execution due to an error in the code. Such error situations, referred to as exceptions, can be overcome by Java.

 


Handling of Exception:

When the Java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it (i.e., informs us that an error has occurred). If the exception object is not caught and handled properly, the interpreter will display an error message and will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as exception handling.

An exception can be generated by the Java run-time system, or they can be generated manually. Exceptions generated (thrown) by Java are errors that violate the rules of the Java language. The Exception handling feature of Java provides a structural method by which run-time errors can be trapped and handled in a program. Java exception handling is managed through five keywords: try, catch, throw, throws and finally.

The basic concepts of exception handling are throwing an exception and catching it. This is illustrated in figure below:





Using try-catch:

The try-catch block is used to handle exceptions in Java. When an error occurs in your program, the code that finds the error can “throw” that exception. Throwing an exception is the process of signaling the current process that an error has occurred. Your program can catch the thrown exception and execute necessary code to recover from the error if possible.


To handle a particular exception, use the try statement with code that might throw that exception. To catch and act on thrown exceptions, use the catch statement to specify both the exceptions to catch and the code to execute if the exception is thrown.

Syntax:

try

{

statement; //generates an exception

}

catch(Exception-type  e)

{

statement;   //processes the exception

}


The try block can have one or more statements that could generate an exception. If any statement generates an exception, the remaining statements in the block are skipped and execution jumps to the catch block that is placed next to the try block.

The catch block too can have one or more statements that are necessary to process the exception. The catch block is added immediately after the try block. Every try block should be followed by at least one catch block.


Program: Using try and catch for exception handling

 

class ExceptionExample

{

  public static void main(String args[])

{

int a=5;
int b=2;
int c=2;
int x,y;

 

   try

    {

    x=a/(b-c);      //Exception here

    }

    catch(ArithmeticException e)

    {

    System.out.println(“Division by zero”);

    }

    y= a/(b+c)
    System.out.println("y= " + y);

  }

}

 


Output:

 

Division by zero

y=1



Catching Multiple Exceptions:

A try block can be followed by any number of catch blocks-only one of them will be executed.

When an exception in a try block is generated, Java treats the multiple catch statements like cases in a switch statement. The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped.

try

{

statement; //generates an exception

}

catch(Exception-type1  e)

{

statement;   //processes the exception

}

catch(Exception-type2  e)

{

statement;     //processes the exception

}

.

.

.

catch(Exception-typeN  e)

{

statement;   //processes the exception

}



Using finally clause:

Java supports another statement known as finally statement. The finally statement defines a block of code that must be executed regardless of whether an exception was caught or not.

 

try

{

……..

……..

}

catch()

{

…………………

………………..

}

finally

{

………………..

………………….

}


Types of Exceptions:

In Java, exceptions can be categorized into two types:


Checked Exceptions: They are checked at compile-time. For example, IOException, InterruptedException, etc.


Unchecked Exceptions: They are not checked at compile-time but at run-time. For example, ArithmeticException,  NullPointerException,  ArrayIndexOutOfBoundsException, exceptions under Error class, etc.


Throwing Exceptions:

There may be times when we would like to throw our own exceptions. The throw keyword in Java is used to throw an exception explicitly. Using throw keyword, we can throw either checked or unchecked exceptions in java programming.

When an exception occurs in the try block, throw keyword transfers the control of execution to the caller by throwing an object of exception.

Only one object of exception type can be thrown by using throw keyword at a time. Throw keyword can be used inside a method or static block provided that exception handling is present.

 

Syntax:

throw new exception_name(); 

where exception name is a reference to an object of Throwable class or its subclass 


Program: Throwing our own exception


import java.lang.Exception;

class MyException extends Exception

{

   MyException()

    {

    System.out.println("Invalid Marks");

    }

}


class test

{

public static void main(String args[])

{

int marks=107;

    try

    {

     if(marks>100)

     throw new MyException();

     System.out.println("marks:" +marks);

     }

    catch(Exception e)

     {

      System.out.println(e);

      }

}

}

 


 


Post a Comment

0 Comments