Showing posts with label Exception Handling. Show all posts
Showing posts with label Exception Handling. Show all posts

Friday, October 16, 2015

Using Throw Keyword (How to manually throw Exception in Java?)

In java we have already defined exception classes such asArithmeticExceptionArrayIndexOutOfBoundsException,NullPointerException etc. There are certain conditions defined for these exceptions and on the occurrence of those conditions they are implicitly thrown by JVM(java virtual machine).
Do you know that a programmer can create a new exception and throw it explicitly? These exceptions are known as user-defined exceptions. In order to throw user defined exceptions, throw keyword is being used. In this tutorial, we will see how to create a new exception and throw it in a program using throw keyword.
You can also throw an already defined exception like ArithmeticException,IOException etc.

Syntax of throw statement

throw AnyThrowableInstance;
Example:
//A void method
public void sample()
{
   //Statements
   //if (somethingWrong) then
   IOException e = new IOException();
   throw e;
   //More Statements
 }
Note:
  • A call to the above mentioned sample method should be always placed in a try block as it is throwing a checked exception – IOException. This is how it the call to above method should be done:
    MyClass obj =  new MyClass();
    try{
          obj.sample();
    }catch(IOException ioe)
     {
          //Your error Message here
          System.out.println(ioe);
      }
  • Exceptions in java are compulsorily of type Throwable. If you attempt to throw an object that is not throwable, the  compiler refuses to compile your program and it would show a compilation error.
Flow of execution while throwing an exception using throw keyword
Whenever a throw statement is encountered in a program the next statement doesn’t execute. Control immediately transferred to catch block to see if the thrown exception is handled there. If the exception is not handled there then next catch block is being checked for exception and so on. If none of the catch block is handling the thrown exception then a system generated exception message is being populated on screen, same what we get for un-handled exceptions.
E.g.
class ThrowDemo{
   public static void main(String args[]){
      try{
    char array[] = {'a','b','g','j'};
    /*I'm displaying the value which does not
     * exist so this should throw an exception
     */
    System.out.println(array[78]);
      }catch(ArithmeticException e){
     System.out.println("Arithmetic Exception!!");
       }
   }
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 
78 at beginnersbook.com.ThrowDemo.main(Details.java:9)
Since the exception thrown was not handled in the catch blocks the system generated exception message got displayed for that particular exception.

Explain Try - Catch in Java

What is Try Block?

The try block contains a block of program statements within which an exception might occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must followed by a Catch block or Finally block or both.

Syntax of try block

try{
   //statements that may cause an exception
}

What is Catch Block?

A catch block must be associated with a try block. The corresponding catch block executes if an exception of a particular type occurs within the try block. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.

Syntax of try catch in java

try
{
     //statements that may cause an exception
}
catch (exception(type) e(object))‏
{
     //error handling code
}

Flow of try catch block

  1. If an exception occurs in try block then the control of execution is passed to the catch block from try block. The exception is caught up by the corresponding catch block. A single try block can have multiple catch statements associated with it, but each catch block can be defined for only one exception class. The program can also contain nested try-catch-finally blocks.
  2. After the execution of all the try blocks, the code inside the finally block executes. It is not mandatory to include a finally block at all, but if you do, it will run regardless of whether an exception was thrown and handled by the try and catch blocks.

An example of Try catch in Java

class Example1 {
   public static void main(String args[]) {
     int num1, num2;
     try { 
        // Try block to handle code that may cause exception
        num1 = 0;
        num2 = 62 / num1;
        System.out.println("Try block message");
     } catch (ArithmeticException e) { 
            // This block is to catch divide-by-zero error
            System.out.println("Error: Don't divide a number by zero");
       }
     System.out.println("I'm out of try-catch block in Java.");
   }
}
Output:
Error: Don't divide a number by zero
I'm out of try-catch block in Java.

Multiple catch blocks in Java

1. A try block can have any number of catch blocks.
2. A catch block that is written for catching the class Exception can catch all other exceptions
Syntax:
catch(Exception e){
  //This catch block catches all the exceptions
}
3. If multiple catch blocks are present in a program then the above mentioned catch block should be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely ignored and the program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.

Example of Multiple catch blocks

class Example2{
   public static void main(String args[]){
     try{
         int a[]=new int[7];
         a[4]=30/0;
         System.out.println("First print statement in try block");
     }
     catch(ArithmeticException e){
        System.out.println("Warning: ArithmeticException");
     }
     catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Warning: ArrayIndexOutOfBoundsException");
     }
     catch(Exception e){
        System.out.println("Warning: Some Other exception");
     }
   System.out.println("Out of try-catch block...");
  }
}
Output:
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes sequentially when an exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the first place, just after try block then in case of any exception this block will execute as it has the ability to handle all exceptions. This catch block should be placed at the last to avoid such situations.

Introduction to Exception Handling in Java

The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.
In this page, we will learn about java exception, its type and the difference between checked and unchecked exceptions.

What is exception

Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

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:
  1. statement 1;  
  2. statement 2;  
  3. statement 3;  
  4. statement 4;  
  5. statement 5;//exception occurs  
  6. statement 6;  
  7. statement 7;  
  8. statement 8;  
  9. statement 9;  
  10. 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.


Do You Know ?
  • What is the difference between checked and unchecked exceptions ?
  • What happens behind the code int data=50/0; ?
  • Why use multiple catch block ?
  • Is there any possibility when finally block is not executed ?
  • What is exception propagation ?
  • What is the difference between throw and throws keyword ?
  • What are the 4 rules for using exception handling with method overriding ?

Hierarchy of Java Exception classes

hierarchy of exception handling

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:
  1. Checked Exception
  2. Unchecked Exception
  3. Error

Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.
  1. int a=50/0;//ArithmeticException  

2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
  1. String s=null;  
  2. System.out.println(s.length());//NullPointerException  

3) Scenario where NumberFormatException occurs

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.
  1. String s="abc";  
  2. int i=Integer.parseInt(s);//NumberFormatException  

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
  1. int a[]=new int[5];  
  2. a[10]=50//ArrayIndexOutOfBoundsException  

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

Difference between throw and throws

1. A throw statement can be used to throw an Exception explicitly from the code where as a throws statement just declares that an Exception can be thrown. It doesn't actually throw and Exception

2.
--A throw statement is followed by an object of type Throwable e.g.

Exception e1=new Exception(); 
throw e1;

-- A throws statement is written in the definition of a constructor or a method e.g.

void m1() throws Exception{
    // any code here
}

3. A throw statement is an executable statement where as a throws statement is just a declarative statement

4. A throw statement is actually used at run time.. where as a throws statement is referred by the compiler at compile time. After compilation, throws has no effect at run time

5. A throw statement is used to throw both Checked and Unchecked Exceptions, while a throws statement should be used if an un-handled Checked exception is throws from a method or constructor.