www.000webhost.com
/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Exception Handling Java Tech Tutorials



Continue/ Next Page


Exception Handling in Java

Core Java

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



Real world Example on exception :-


For example, if our program needs to access a file which is located in London and it isn’t available at the moment then it shouldnt be terminated abnormally, we have to provide some alternative to continue rest of program (like providing a local file). This way of defining an alternative is known as “Exception handling”.


Default Exception handling in Java :-



Inside any method if any exception occurs, then the method in which Exception has occurred is responsible for the preparation of exception object by including the following information.


Exception flow



exceptionFlow.png exceptionobjecthandling

Here is an Example :-

class  Test
{
	public static void main(String[] args) 
	{
		doStuff();
	}
	 public static void doStuff()
	{
		doMoreStuff();
	}
      public static void doMoreStuff()
	{
		System.out.println(10/0);
	}
}

//When you try to execute the code the following can be seen on console
Output :-
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Test.doMoreStuff(Exceptiondemo.java:13)
at Test.doStuff(Exceptiondemo.java:9)
at Test.main(Exceptiondemo.java:5)

Another Example with handling the exception


class Simple{
  public static void main(String args[]){
   try{
      int data=50/0;
  
   }catch(ArithmeticException e){System.out.println(e);}
	
   System.out.println("rest of the code...");
}
}

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


Exception Handling Keywords

Java provides specific keywords for exception handling purposes, we will look after them first and then we will write a simple program showing how to use them for exception handling.


throw :–


We know that if any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime we might want to generate exception explicitly in our code.
for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the runtime to handle it.

By using throw keyword, we can create our own exception object manually. In general, we use throw for customized exception but not for manual exception. We cannot write any statement after throw , otherwise we would get compile time error saying “Unreachable statement.” We can use throw keyword only for throwable type otherwise we will get compile time error saying incompatible type.


throws :–


When we are throwing any exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.


try-catch :–


We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.


finally :–


finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.


Exception Hierarchy :-

Throwable class acts as root for exception hierarchy.
Throwable class contains two child classes


Exception :-


In most of the cases these are caused by programs and all are recoverable.


Error :-


Errors are not caused by program and these are typically due due to lack of system resources. These are non-recoverable.
Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them,
for example hardware failure, JVM crash or out of memory error.
we should not try to handle these situations. Some of the common Errors are OutOfMemoryError and StackOverflowError



Checked vs Unchecked Exceptions


Checked Exceptions :-


The exceptions that are checked by the compiler for smooth execution of program are know as Checked Exception. We should handle checked exceptions in our program to compile.
for example - FileNotFoundException.
We should catch these exception and provide useful message to user and log it properly for debugging purpose.
Exception is the parent class of all Checked Exceptions and if we are throwing a checked exception, we must catch it in the same method or we have to propagate it to the caller using throws keyword.

Common scenarios of Exception, where exceptions may occurs :-



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

ArithmeticException :-


If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

NullPointerException :-


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

NumberFormatException


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

ArrayIndexOutOfBoundsException :-


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


Unchecked/Runtime Exceptions :-



These are not checked by the compiler. Hence Unchecked ! They occur in runtime.
Runtime Exceptions are cause by bad programming,
for example :-
trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime.


Handling Exception by using try-catch-finally :-


NOTE :-

We must handle the exception to prevent abnormal execution of program. The code which may cause exception is known as risky code .
We must keep this risky code in try and corresponding handling code in catch.
If we need some code which have to be executed no matter exception rises or not, then we should declare it in a finally block.



Multiple catch block :-


If you have to perform different tasks at the occrence of different Exceptions, use multple catch block.

At a time only one Exception is occured and at a time only one catch block is executed.
Rule:All catch blocks must be ordered from most specific to most general
i.e. catch for ArithmeticException must come before catch for Exception .


Example of multiple catch block :-

class MultipleCatchExample{
  public static void main(String args[]){
   try{
    int a[]=new int[5];
    a[5]=30/0;
   }
   catch(ArithmeticException e){System.out.println("task1 is completed");}
   catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
   catch(Exception e){System.out.println("common task completed");}

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

Output:
		task1 completed
       	rest of the code...

Nested try block :-


Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested


Example of nested try block :-

class NestedTryExample{
 public static void main(String args[]){
  try{
    try{
     System.out.println("going to divide");
     int b =39/0;
    }catch(ArithmeticException e){System.out.println(e);}

    try{
    int a[]=new int[5];
    a[5]=4;
    }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

    System.out.println("other statement);
  }catch(Exception e){System.out.println("handeled");}

  System.out.println("normal flow..");
 }
}

throw keyword :-


The throw keyword is used to explictily throw an exception.


By using throw keyword, we can create our own exception object manually. In general, we use throw for customized exception but not for manual exception.
We cannot write any statement after throw , otherwise we would get compile time error saying “Unreachable statement.”
We can use throw keyword only for throwable type otherwise we will get compile time error saying incompatible type.
//For example below program is n't correct and hence we will get error.
	 class Test
	{
		public static void main(String[] args)
		{
			throw new Test();
		}
	}
	/* Test.java:5: error: incompatible types
	                throw new Test();
	                      ^
	  required: Throwable
	  found:    Test
	1 error*/
	________________________________________

	//correct implementation is
	class Test extends RuntimeException
	{
	public static void main(String[] args)
	{
		throw new Test();
	}
}

 

Example of throw keyword :-

class ThrowExceptionExample{

   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

Creating Your Own Exception Classes - Custom Exception:-

If you are creating your own Exception that is known as custom exception or user-defined exception.

You should try to reuse the Exception classes provided in the JDK, e.g., IndexOutOfBoundException, ArithmeticException, IOException, and IllegalArugmentException. But you can always create you own Exception classes by extending from the class Exception or one of its subclasses.


Custom exception example :-

// Create our own exception class by subclassing Exception. This is a checked exception
public class MyMagicException extends Exception {
   public MyMagicException(String message) {  //constructor
      super(message);
   }
}

public class MyMagicExceptionTest {
   // This method "throw MyMagicException" in its body.
   // MyMagicException is checked and need to be declared in the method's signature
   public static void magic(int number) throws MyMagicException {
      if (number == 8) {
         throw (new MyMagicException("you hit the magic number"));
      }
      System.out.println("hello");  // skip if exception triggered
   }

   public static void main(String[] args) {
      try {
         magic(9);   // does not trigger exception
         magic(8);   // trigger exception
      } catch (MyMagicException ex) {   // exception handler
         ex.printStackTrace();
      }
   }
}

 Output :-
	hello
	MyMagicException: you hit the magic number
	        at MyMagicExceptionTest.magic(MyMagicExceptionTest.java:6)
	        at MyMagicExceptionTest.main(MyMagicExceptionTest.java:14)
Exception_Classes

Continue/ Next Page
Click here to access OOp's Concept

feel free to ask any of your doubts