Java : Exception Handling


 

Java : Exception Handling

In this section we will discuss about JAVA Exception Handling with simple example.

In this section we will discuss about JAVA Exception Handling with simple example.

Java : Exception Handling

In this section we will discuss about  JAVA Exception Handling with simple example.

Exception Handling :

An exception is an event that create problem at the time of program execution. It disturb your normal execution of program.
There are many reason of exceptions -

  • Dividing any number by zero.
  • User inputted wrong data.
  • Accessing elements out of range of an array .
  • Hard disk crash.
  • At the time of communications, network connection has been lost or jvm has run out of memory.
  • user trying to open such file which doesn't exist.

By default it is handled by java runtime and also generates error message ,which is displayed  and it causes the program termination.

You  can handle exceptions by using try/catch block. Put all the code in try block which may cause any kind of exceptions and a catch block helps in throwing exception.

Example :

import java.util.Scanner;

class ExceptionHandling {
public static void main(String[] args) {
int x, y, result;
Scanner input = new Scanner(System.in);
try {
System.out.println("Input x : ");
x = input.nextInt();
System.out.println("Input y : ");
y = input.nextInt();
result = x / y;
System.out.println("value of (x/y) = " + result);
} catch (Exception e) {
System.out.println("Divided by zero exception.");
}
}
}

Description :In this example we are using try and catch block to handle exception. We put all the code in try block which may cause any kind of exception. As in this example we are inputting two int type variable x and y and will put this code into try block. Next result is int type variable which holds value of x/y and finally printing it. If there is no exception then it will print result otherwise it will jump into catch block. Suppose we are inputting value of x=5 and value of y=0 so it will generate exception at the time of calculating result. So catch block will execute and it will print message "Divided by zero exception.".

Output :

Input x : 
5
Input y : 
0
Divided by zero exception.

Ads