Programmer Coding

Exception Handling

The exception handling in java is one of the powerful tool to   handle   the   runtime errors so that normal flow of the application can be reconstructed.

 

What is exception

 

In java, exception is an incident that reduces the normal flow of the program. It is an object which is thrown at runtime.

 

Advantage of Exception Handling

 

The core advantage of exception handling is to maintain the normal flow of the application. Exception genrely reduces the normal flow of the application that is why we use 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

 

  • Checked Exception: The classes that extend knowable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
  • Unchecked Exception: The classes that extend RuntimeException are known as unchecked exceptions g. ArithmeticException, Null Pointer Exception, Array Index out of Bounds Exception etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
  • Error: Error is irrecoverable g. out of Memory Error, Virtual Machine Error, Assertion Erroretc.

 

Ranking of Java Exception classes

 

 

 

 

 Checked and UnChecked Exceptions

 

 

Java try block

 

Java try block is used to enclose the code that might throw an exception. It must be used enclosed by the way(method) .

 

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

 

Syntax of java try-catch

 

  1. try{
  2. //code that may throw exception
  3. }catch(Exception_class_Name ref){} Syntax of try-finally block
  4. try{
  5. //code that may throw exception
  6. }finally{}

 

Java catch block

 

Java catch block is used to handle the Exception. It must be used after the try block.

You can use multiple catch block with a single try.

Problem without exception handling

 

Let’s try to understand the problem if we don’t use try-catch block.

 

public class Testtrycatch1{

public static void main(String args[]){ int data=50/0;//may throw exception System.out.println(“welcome to progremercoding.com”);

} }

Output:

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

 

As out put in the above example, rest of the code is not applied (in such case, rest of the code… statement is not printed).

 

There can be 100 lines of code after exception. So all the code after exception will not be applied.

 

Solution by exception handling

 

Let’s see the solution of above problem by java try-catch block.

 

public class Testtrycatch2{

 

public static void main(String args[]){

try{

int data=50/0;

}catch(ArithmeticException e){System.out.println(e);} System.out.println(“welcome to progremercoding.com.”);

} }

Output:

Exceptioninthreadmainjava.lang.ArithmeticException:/byzero

welcome to progremercoding.com.

 

 

Now, as out put in the above example, rest of the code is applied i.e. welcome to progremercoding.com statement is printed.

 

Java Multi catch block

 

If you have to apply different tasks at the

incident of different Exceptions, use java multi catch block.

 

Let’s see a simple example of java multi-catch block.

 

  1. public class TestMultipleCatchBlock{
  2. public static void main(String args[]){
  3. try{
  4. int a[]=new int[5]; a[5]=30/0;
  5. }
  6. catch(ArithmeticException e){System.out.println(“task1 is completed”);}
  7. catch(ArrayIndexOutOfBoundsException e){System.out.println(“task2 completed”); }
  8. catch(Exception e){System.out.println(“frequenttask completed”);
  9. }
  10. System.out.println(“welcome to progremercoding.com.”);
  11. } }

 

Output:task1 completed

welcome to progremercoding.com

 

Java nested try example

 

Let’s see a simple example of java nested try block.

 

class Excep6{

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 of code..”);

} 1. }

Java finally block

 

Java finally block is a block that is used to apply important code such as closing connection, flow etc.

 

Java finally block is a way(method) s applied whether exception is handled or not. Java finally block follows try or catch block.

 

 

Usage of Java finally

 

Case 1

Let’s see the java finally example where exception doesn’t happen. class TestFinallyBlock{

public static void main(String args[]){

try{

int data=25/5; System.out.println(data);

}

catch(NullPointerException e){System.out.println(e);} finally{System.out.println(“finally block is alway(method) s applied”);} System.out.println(“rest of the code…”);

}

Output:5

finally block is always executed

rest of the code…

}

 

Java throw keyword

 

The Java throw keyword is used to definitively throw an exception.

 

We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw random  exception. We will see random  exceptions later.

 

The syntax of java throw keyword is given below.

 

  1. throw exception;
Java throw keyword example

 

In this example, we have produced the validate way(method)  that takes integer value as a parameter. If the age is less than 18, we are throwing the Arithmetic Exception other wise print a message welcome to vote.

 

  1. public class TestThrow1{

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 alternate main java.lang.ArithmeticException:not valid

Java throws keyword

 

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may happen an exception so it is best for the programmer to provide the exception handling code so that normal flow can be reconstructed.

 

Exception Handling is mainly used to handle the checked exceptions. If there happens any unchecked exception such as Null Pointer Exception, it is programmers fault that he is not applying check up before the code being used.

 

Syntax of java throws

  1. return_type way(method) _name() throws exception_class_name{
  2. //way(method) code
  3. }

4.

 

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 Testthrows1{

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[]){ Testthrows1 obj=new Testthrows1(); obj.p();

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

Output:

exception handled

normal flow…

Java Random  Exception

 

If you are creating your own Exception that is known as random  exception or user-circle exception. Java random  exceptions are used to random ize the exception according to user need.

 

By the help of random  exception, you can have your own exception and message. Let’s see a simple example of java random  exception.

class InvalidAgeException expand Exception{ InvalidAgeException(String s){

super(s);

} }

class TestRandomException1{

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 happened: “+m);}

 

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

} }

 

Output:

Exception happened:

InvalidAgeException:

not valid rest of the code…

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top