bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

Java Exception Handling

 

Exception is a run time error that means the error which is occurred during the execution of program. When an exception is occurred then program is terminated in abnormal condition. Exceptions are occurred due to following reasons:

  • When user enter invalid value
  • A file that requires to be opened cannot be found.
  • JVM has run out of memory etc.

 

There are 3 types of exceptions which are:

1. Checked Exceptions: These are also called as compile time exceptions. It is an exception that occurs at the compile time. These exceptions are checked at the compile time by the programmers.

2. Unchecked Exceptions: These are also called as run time exceptions. It is an exception that occurs at the run time. These exceptions are not checked at compile time rather they are checked at run time. It includes logical errors, improper use of API etc.

3. Errors: These are the problems which occur beyond the control of the user or the programmer. For example, OutOfMemoryError, VirtualMachineError etc.

 

Exception Hierarchy

exception hierarchy

Exception handling – It is a mechanism which is used to handle the exception. Five keywords are used to handle exception handling in java.

 

1. Try block – It includes the code that might throw an exception. It is followed by either finally or catch block.

try {

code

}

catch and finally blocks

 

2. Catch Block – It is used to handle exception. The catch block contains code that is executed if and when the exception handler is invoked. It must be used after the try block only. It is also possible to use multiple catch block for single try block.

Problem without Exception Handling

public class Intellipaat{

public static void main(String args[]){

int i=40/0; // Exception

System.out.println("Program exceuted”);

}

}

Output

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

at Intellipaat.main(Intellipaat.java:3)

 

So to handle this type of exception, exception handling is used.

public class Intellipaat{

public static void main(String args[]){

try{

int i=40/0;  // Exception

}

catch(ArithmeticException e){ // Handle Exception

System.out.println(e);

}

System.out.println("Program Executed");

}

}

Output

java.lang.ArithmeticException: / by zero

Program Executed

 

First of all Java Virtual Machine checks that whether the exception is handled or not, if exception is not handled, JVM provides a default exception handler which performs the following tasks:

  • Print exception description.
  • Print the stack trace
  • Causes the program to terminate.

But if exception handling is used then normal flow of the program is maintained and rest of the code is executed.

 

Multi Catch Block 

Within the try block when exception is thrown then type of the exception thrown is compared with the type of exception of every catch block. If type of exception thrown is matched with the type of exception from catch then it will execute corresponding catch block. But at a time one Exception is occurred and only one catch block is executed. All the exceptions or catch blocks must be arranged in order.

e.g.

public class MultiCatch{

int c;

public static void main(String args[]){

try{

int a=10/0;

}

catch(ArithmeticException e){

System.out.println("Arithmetic Exception Occurred");

}

catch(ArrayIndexOutOfBoundsException e){

System.out.println("Array Index out of bound Exception Occurred ");

}

catch(Exception e){

System.out.println("Exception is found");

}

System.out.println("Program executed");

}

}

Output

Arithmetic Exception Occurred

Program executed

 

Nested try block

The try block within a try block is known as nested try block.It is used to

e.g.

public class NestedTry

{

public static void main(String args[])

{

try {

try {

int a =40/0;

}

catch(ArithmeticException e){

System.out.println(e);

}

try{

int b[]=new int[10];

b[10]=20;

}

catch(ArrayIndexOutOfBoundsException e){System.out.println(e);

}

}catch(Exception e){

System.out.println(e);

}

System.out.println("Exception handled");

}

}

Output

java.lang.ArithmeticException: / by zero

java.lang.ArrayIndexOutOfBoundsException: 10

Exception handled

 

Java finally block

It executes important code like as stream, closing connection etc. It must be followed by try or catch block. It is always executed whether an exception is handled or not.

e.g.

public class FinallyBlock{

public static void main(String args[]){

try{

int i=20/0;

}

catch(ArithmeticException e){

System.out.println(e);

}

finally{

System.out.println("Always Exceuted");

}

System.out.println("Exception Handled");

}

}

Output

java.lang.ArithmeticException: / by zero

Always Exceuted

Exception Handled

 

Java throw exception

Keyword throw is used to throw exception explicitly. You can throw checked and unchecked exception. It is mainly used to handle the custom exception. Custom exceptions are those exceptions which are created by user.

public class ExceptionThrow{

static void edetails(int salary){

if(salary<10000)

throw new ArithmeticException("Not valid");

else

System.out.println("Salary is greater than 10000");

}

public static void main(String args[]){

edetails(5000);

System.out.println("Program executed");

}

}

Output

Exception in thread “main” java.lang.ArithmeticException: Not valid

 

throws keyword

It declares an exception. It provides information to the programmer that exception may occur so they can handle exception so program can run in normal flow.  Checked Exception can be propagated by using throw keyword.

 e.g.

import java.io.*;

public class ExceptionThrow{

void sample()throws IOException

{

throw new IOException("");//checked exception

}

void sample1()throws IOException{

sample ();

}

void sample2()

{

try{

sample1();

}catch(Exception e){

System.out.println("Exception handled");

}

}

public static void main(String args[]){

ExceptionThrow t=new ExceptionThrow ();

t.sample2();

System.out.println("Program Exceuted");

}

}

Output

Exception handled

Program Exceuted

Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

"0 Responses on Java Exception Handling"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

top

Sales Offer

  • To avail this offer, enroll before 05th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free Java Exception Handling.