Exception Handling in Java - Passionate Geekz

Breaking

Where you can unleash your inner geek.

Saturday, 25 January 2020

Exception Handling in Java

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.

Java Exception are two types checked and unchecked

What is Exception in Java

Dictionary Meaning: Exception is an abnormal condition.

In Java, an 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 ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application that is why we use exception handling. 

  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 are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:

hierarchy of exception handling

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:

  1. Checked Exception
  2. Unchecked Exception
  3. Error
Types of Java Exceptions

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit 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 which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

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

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

KeywordDescription
tryThe “try” keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone.
catchThe “catch” block is used to handle the exception. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later.
finallyThe “finally” block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throwThe “throw” keyword is used to throw an exception.
throwsThe “throws” keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

Common Scenarios of Java Exceptions

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

1) A scenario where ArithmeticException occurs

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

  1. int a=50/0;//ArithmeticException  

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.

  1. String s=null;  
  2. System.out.println(s.length());//NullPointerException  

3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters, converting this variable into digit will occur NumberFormatException.

  1. String s=“abc”;  
  2. int i=Integer.parseInt(s);//NumberFormatException  

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:

  1. int a[]=new int[5];  
  2. a[10]=50; //ArrayIndexOutOfBoundsException  

Java Exceptions Index

  1. Java Try-Catch Block
  2. Java Multiple Catch Block
  3. Java Nested Try
  4. Java Finally Block
  5. Java Throw Keyword
  6. Java Throws Keyword
  7. Java Throw vs Throws
  8. Java Final vs Finally vs Finalize
  9. Java Custom Exceptions

1). Java Try-Catch Block

Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.

Java try block must be followed by either catch or finally block.

Java catch block

Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch block with a single try block.

Example 1:- To use single Catch to solve Arithmetic Exception

public class Exception1st
{

public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println(“Can’t divided by zero”);
}
}
}

Example 2:- To use single Catch to solve Array out of Bound of Exception

public class Exception2nd
{

public static void main(String[] args)
{
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println(“Array out of Bound Exception”);
}
}

Example 3:In this example show how to handle exception

public class Exceptionhandle
{

public static void main(String[] args)
{
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}

2).Java Multiple Catch Block

A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.

Points to remember

  • At a time only one exception occurs and at a time only one catch block is executed.
  • All catch blocks must be ordered from most specific to most general, i.e. catch for Arithmetic Exception must come before catch for Exception.

Example 1:

In this Example we check for arithmetic exception.

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

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println(“Arithmetic Exception occurs”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“ArrayIndexOutOfBounds Exception occurs”);
}
catch(Exception e)
{
System.out.println(“Parent Exception occurs”);
}
System.out.println(“rest of the code”);
}
}

Example 2:

In this Example we check for ArrayIndexOutOfBoundsException

public class Exception4th
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println(“Arithmetic Exception occurs”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“ArrayIndexOutOfBounds Exception occurs”);
}
catch(Exception e)
{
System.out.println(“Parent Exception occurs”);
}
System.out.println(“rest of the code”);
}
}

3).Java Nested try block

The try block within a try block is known as nested try block in java.

Why use 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 1:

public class Exception5th
{
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..”);
}
}

4).Java 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.

java finally


Example 1:

public class Exceptionfinally
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println(“finally block is always executed”);
}
System.out.println(“rest of the code…”);
}
}

5).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. 

The syntax of java throw keyword is given below.

Example 1:
public class Exceptionthrow
{
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…”);
}
}

6).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.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception

Example 1:

import java.io.IOException;
public class Exceptionthrows
{
void m()throws IOException
{
throw new IOException(“device error”);//checked exception
}
void p()
{
try
{
m();
}
catch(Exception e)
{
System.out.println(“exception handled”);
}
}
public static void main(String args[])
{
Exceptionthrows obj=new Exceptionthrows ();
obj.p();
System.out.println(“normal flow…”);
}
}

Example 2:-

import java.io.*;
class Exceptionthrows1st
{
void method()throws IOException
{
System.out.println(“device operation performed”);
}
}
class Testthrows3
{
public static void main(String args[])throws IOException{//declare exception
Exceptionthrows1st m=new Exceptionthrows1st();
m.method();

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

Example 3:-

import java.io.*;
class Exceptionthrows2nd
{
void method()throws IOException
{
throw new IOException(“device error”);
}
}
class Testthrows4
{
public static void main(String args[])throws IOException
{//declare exception
Exceptionthrows2nd m=new Exceptionthrows2nd();
m.method();

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

7).Difference between throw and throws in Java

There are many differences between throw and throws keywords. A list of differences between throw and throws are given below:

No.throwthrows
1)Java throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.
2)Checked exception cannot be propagated using throw only.Checked exception can be propagated with throws.
3)Throw is followed by an instance.Throws is followed by class.
4)Throw is used within the method.Throws is used with the method signature.
5)You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.

8).Difference between final, finally and finalize

There are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:

No.finalfinallyfinalize
1)Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.Finally is used to place important code, it will be executed whether exception is handled or not.Finalize is used to perform clean up processing just before object is garbage collected.
2)Final is a keyword.Finally is a block.Finalize is a method.

Example 1:

public class finalkeyword
{
public static void main(String[] args)
{
final int x=100;
x=200;//Compile Time Error  
}
}

Example 2:

public class finalblock
{
public static void main(String[] args)
{
try
{
int x=300;
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println(“finally block is executed”);
}
}
}

Example 3:

class Finalmethod
{
public void finalize()
{
System.out.println(“finalize called”);
}
public static void main(String[] args)
{
Finalmethod f1=new Finalmethod();
Finalmethod f2=new Finalmethod();
f1=null;
f2=null;
System.gc();
}
}

Custom Exception

If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let’s see a simple example of java custom exception.

class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
public class Exceptioncustom
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException(“not valid”);
else
System.out.println(“welcome to vote”);
}

public static void main(String args[])
{
try
{
validate(13);
}catch(Exception m)
{System.out.println(“Exception occured: “+m);
}

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

No comments:

Post a Comment