CORE JAVA: Exception Handling

Introduction

  • An exception is a run-time error
  • This means it is an abnormal condition that arises in a code sequence at run time
  • Java exception handling is managed via five keywords: try, catch, throw, throws, and finally

11

Advantage of Exception Handling:

The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let’s take a scenario:

 statement 1;  

statement 2;  

statement 3;  

statement 4;  

statement 5;//exception occurs  

statement 6;  

statement 7;  

statement 8

statement 9;  

statement 10;  

Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java.


Pre-Defined Exceptions

12.png

Built-in Exceptions:

Three Categories

•Unchecked Exceptions

–Not essentially handled in the program code

–Compiler does not check to see if a method handles or throws these exceptions

–Extended from java.lang.RuntimeException

•Checked Exceptions

–Mandatory to handle them in the program code

–Extended from java.lang.ExceptionError

Error – OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur:

  1. If we divide any number by zero, there occurs an ArithmeticExceptionint a=50/0;    //ArithmeticException 
  2. If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.

    String s=null;  

    System.out.println(s.length());  //NullPointerException

  3. The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.String s=“abc”; int i=Integer.parseInt(s);  //NumberFormatException  
  4. If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:int a[]=new int[5];  a[10]=50;  //ArrayIndexOutOfBoundsException

Try-Catch-Finally

Try Block:

  • Java try block is used to enclose the code that might throw an exception. It must be used within the method.
  • Java try block must be followed by either catch or finally block.

Catch Block:

  • Java catch block is used to handle the Exception. It must be used after the try block only.
  • You can use multiple catch block with a single try.

Finally Block:

  • Java finally block is a block that is used to execute important code such as closing connection, stream etc.
  • Java finally block is always executed whether exception is handled or not.
  • Java finally block follows try or catch block.

13.JPG

Syntax:

14.jpg

Example 1:

Problem without exception handling

public class Test1{  

  public static void main(String args[]){  

      int data=50/0;  //may throw exception  

      System.out.println(“rest of the code…”);  

}  

}  

output:

Exception in thread main java.lang.ArithmeticException:/ by zero

Solution by exception handling

public class Test2{

public static void main(String args[]){

try{

int data=50/0;

}catch(ArithmeticException e){System.out.println(e);}

finally {System.out.println(“Finally block..”);}

System.out.println(“rest of the code…”);

}

}

output:

Exception in thread main java.lang.ArithmeticException:/ by zero
Finally block
rest of the code...

Example 2:

public class Test3{

public static void main(String args[]){

try{

int data=25/0;

System.out.println(data);

}

catch(ArithmeticException e){System.out.println(e);}

finally{System.out.println(“finally block is always executed”);}

System.out.println(“rest of the code…”);

}

}

output:

Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...

Java throws keyword

  • The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
  • Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.

Syntax of java throws:

return_type  method_name()  throws  exception_class_name{  

//method code 

}  

Java throws example:

Let’s see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword.

 

import java.io.IOException;  

class Testthrows{  

  void m() throws IOException{  

    throw new IOException(“device error”); //checked exception  

  }  

  void n() throws IOException{  

    m();  

  }  

  void p(){  

   try{  

    n();  

   }catch(Exception e){System.out.println(“exception handled”);}  

  }  

  public static void main(String args[]){  

   Testthrows obj=new Testthrows();  

   obj.p();  

   System.out.println(“normal flow…”);  

  }  

}  

Output:

exception handled
normal flow...
There are two cases:

  1. Case1:You caught the exception i.e. handle the exception using try/catch.
  2. Case2:You declare the exception i.e. specifying throws with the method.

Java throw keyword

  • The Java throw keyword is used to explicitly throw an exception.
  • We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later.

Syntax of java throw:

throw exception;

Java throw example:

In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.

 

public class TestThrow{  

   static void validate(int age){  

     if(age<18)  

      throw new ArithmeticException(“not valid”);  

     else  

      System.out.println(“welcome to vote”);  

   }  

   public static void main(String args[]){  

      validate(13);  

      System.out.println(“rest of the code…”);  

  }  

}  

Output:

Exception in thread main java.lang.ArithmeticException:not valid

User defined exception in java

User defined exceptions in java are also known as Custom exceptions. Most of the times when we are developing an application in java, we often feel a need to create and throw our own exceptions. These exceptions are known as User defined or Custom exceptions. In this tutorial we will see how to create and throw such  exceptions in a java program.

How to create user defined Exception?

class MyException extends Exception{
    String str1;
    MyException(String str2) {
       str1=str2;
    }
    public String toString(){ 
       return ("Output String = "+str1) ;
    }
}

class CustomException{
    public static void main(String args[]){
       try{
          throw new MyException("Custom");
          // I'm throwing user defined custom exception above
       }
       catch(MyException exp){
          System.out.println("Hi this is my catch block") ;
          System.out.println(exp) ;
       }
    }
}

Output:

Hi this is my catch block
Output String = Custom

Example1:

class WrongInputException extends Exception {
WrongInputException(String s) {
super(s);
}
}
class Input {
void method()  throws WrongInputException {
throw new WrongInputException(“Wrong input”);
}
}
class TestInput {
public static void main(String[] args){
try {
new Input().method();
}
catch(WrongInputException wie) {
System.out.println(wie.getMessage());
}
}
}

Output:

Wrong input

Example2: 

class MyException extends Exception
{
private int ex;
MyException(int a)
{
ex=a;
}
public String toString()
{
return “MyException[” + ex +”] is less than zero”;
}
}

class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a); //calling constructor of user-defined exception class
}
else
{
System.out.println(a+b);
}
}

public static void main(String[] args)
{
try
{
sum(-10, 10);
}
catch(MyException me)
{
System.out.println(me); //it calls the toString() method of user-defined Exception
}
}
}

 Output:

MyException[-10] is less than zero

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s