Exception Handling

Exception handling:

Exception is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disturbed and the program terminates abnormally, the abnormal termination of a program or application is not recommended in usual practice, therefore these exceptions are need to be handled.

An exception can occur for many different reasons, below given are some scenarios where exception occurs.

  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • User is trying to fill up an array beyond its memory limit.
  • Divide by zero
  • A Network connection is terminated.

Few exceptions are due to by user error, others are programming error and others are due to physical resources that have failed in by any reason.

Based on these we have below categories of Exceptions

Checked exceptions: A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation, the Programmer should take care of (handle) these exceptions.

For example,the FileReader class in reads data from a file, if the file specified  doesn’t exist, then the exception FileNotFoundException occurs, and compiler gives error , in order to handle the exception.

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 anArrayIndexOutOfBoundsExceptionexception occurs.

Below diagram shows the class hierarchy of exception classes. it is basically derived from java.lang class. Throwable is the base class of exception with is derived from object class. there are 2 main subclasses of Throwable class Errors and exceptions. Exceptions can be run time exception or other exceptions.

exception-handling-class-hierarchy

There are 3 ways to handle the exception

Try catch | Throw  | throws

1. Using Try Catch

consider below code

public class MyException {
    public static void main(String[] args )
    {

        int a=10;
        int b=20;
        int c=0;

        int d;
      try {
           d=b/c;
       }
     catch (Exception e)
       {
           System.out.println(e);
           e.printStackTrace();
       }
       finally
       {
        System.out.println("Inside Finally");
       }
       System.out.println(c); 
  System.out.println("Renuka is learning Exception Handling"); 
}
  } 

 

in the above code the Statement  d=b/c will generate ambiguous result i.e.e we are trying to divide by a zero which is infinity. So the program will terminate and will not execute the rest of the code. if it is not handled. so we have used a try catch block. so even if any statement inside the try block throws exception the rest of the statements will execute.

finally block is executed even if there is exception or not.

2. Throws

The throws keyword is used in method declaration, in order to explicitly specify the exceptions that a particular method might throw. When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions.When defining a method you must include a throws clause to declare those exceptions

Syntax of throws keyword

void method() throws Exception1,Exception2
{
 Statement1;
 Statement2;
}

Example of throws


class ThrowExample
{
   static void throwMethod() throws ArithmeticException
   {
       System.out.println ("Inside throwMethod");
       throw new ArithmeticException ("Throw example"); 
   } 
   public static void main(String args[])
   {
       try
       {
          throwMethod();
       }
       catch (ArithmeticException exp)
       {
          System.out.println ("The exception get caught" +exp);
       }
    }
}

 

3. The keyword throw 

The Java throw keyword is used to explicitly throw an exception. Checked or unchecked both the exceptions in java can be thrown by throw keyword. Below is the syntax of throw keyword in java.

throw exception;

 

java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter. If the Marks value is less than 40, we are throwing the ArithmeticException otherwise print a message PASS.


public class MyThrow{

static void checkMarks(int age){

if(age<40)

throw new ArithmeticException("Failed");

else

System.out.println("PASS");

}

public static void main(String args[]){

checkMarks (13);

System.out.println("rest of the code");

}

} 

Output:

Exception in thread main java.lang.ArithmeticException:Failed


Search

Subscribe to YouTube

Training on Selenium

Like us on facebook

Jobs

Jobs

Cooking with Amol