6 Exception Handling
An Exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.A user has entered an invalid data.A file that needs to be opened cannot be
found.
A network connection has been lost in the middle of communications or the JVM has run out of
memory.Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to know
how exception handling works in Java.
Exception: An Exception is an unwanted or unexpected event which occurs during the execution
of a program i.e. at runtime that disrupts the normal flow of the program is an exception
The Exception Handling :-Is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.
Difference Between Exception And Error
Exception Error
1.Exception occurs because of our Program. 1.Errors occurs because of lack
of system resources.
2.Exception are recoverable i.e. Programmer can 2.Errors are not recoverable i.e.
handle using try catch block. programmer can handle them to
their level.
3.Exception are two types 3.Errors are only one type
1.CompileTime Exception(Checked Exception) 1. Runtime Exception(Unchecked
2.Runtime Exception(Unchecked Exception) Exception)
Dealing with Errors :-The mission of exception handling is to transfer control from where the
error occurred to an error handler. To handle exceptional situation in your program you must
known the types of error and problems that may occur.
Types of Error:-
1)Compile Time Error:-All syntax error will be detected and displayed by the java compiler and
therefore these errors are known as compile time error.
Runtime Error:-Sometimes a program may compile successfully creating the class. File but may
not run properly such program may produce wrong result due to wrong logic or may terminate
due to error
Following are some most common run time errors
1.Dividing an integer by zero.
2.Accessing an element that is out of an array.
3.File errors fall into this category.
Types of Exception:-
In java all exception are represented by classes. All exception classes are divide from a class
called Throw able. Thus Throw able is at the top of the exception class hierarchy.
1.ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2.ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
3.IOException
It is thrown when an input-output operation failed or interrupted.
4.RuntimeException
This represents any exception which occurs during runtime.
// Java program to demonstrate Arithmetic Exception
class ArithmeticException
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0"); }}}
Output:-Can't divide a number by 0
// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
} catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds"); }}}
Output:Array Index is Out Of Bounds
Java Exception Keywords:-There are 5 keywords which are used in handling exceptions in
Java.
Keyword Description
try The "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.
catch The "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.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "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.
Syntax:- try{
//code
}
Catch(Exception ClassName ref.var.name)
{
//handling code
}
How To Throw Exception:-The java throw keyword is used to explicitly throw an exception.
We can throw either checked or unchecked exception in java by throw keyword.The throw
keyword is mainly used to throw custom exception.
General form:-
type method-name(parameter list)throws exception
{
body of method
}
Here exception list is a comma separated list of the exception that a method can throw
Catching Exception:- It is very easy to throw an exception but some code has to catch the
exception. Catching exception requires more planning if an exception occurs that is not caught
Any where,the program will terminate and print message to console window.
To catch an exception we have to setup try/catch block.
Syntax:- try { //risk code }
Catch(Exception ClassName ref.var.name)
{
//handling code
}
If any of the code inside the try block throws an exception then
1.The program skips the remainder of the code in the try block.
2.The program executes the handler code inside the catch clause. If none of the code inside
the try block throws an exception then the program skips the catch clause.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
}}
Compile by: javac TryCatchExample1.java
Run by: java TryCatchExample1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TryCatchExample1.main(TryCatchExample1.java:5)
As displayed in the above example, the rest of the code is not executed (in such case, the 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 executed.
Solution by exception handling:-
public class TryCatchExample2
{
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");}}
Compile by: javac TryCatchExample2.java
Run by: java TryCatchExample2 java.lang.ArithmeticException: / by zero
rest of the code Now, as displayed in the above example, the rest of the code is executed, i.e.,
the rest of the code statement is printed.
In this example, we also kept the code in a try block that will not throw an exception
public class TryCatchExample3 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}}}
Compile by: javac TryCatchExample3.java
Run by: java TryCatchExample3 java.lang.ArithmeticException: / by zero
Exception Handling Mechanism:-
1.If an exception occurs that is not caught anywhere in a non-graphical application, the program
will terminate
and print a message to the console giving the type of exception and stack traced(the infor about
exception occur)
2.A graphics program prints the same error message but the program goes back to its user
interface processing loop
3.To catch an exception, you set up a try/catch block. The simplest form of the try block is as
follows;
try
{
code
more code
}
catch(Exception Type e)
{
handler for this type
}
4.If any of the code inside the try block throws an exception of the class specified in the catch
clause then
The program skips the remainder of the code in the try block.
The program executes the handler code inside the catch clause.
5.If none of the code inside the try block throws an exception then the program skips the catch
clause.
6.If any of the code in a method throws an exception of type other than the one named in the
catch clause,this method exits immediately and if no handler was there, your program will
terminate.
Catching Exceptions:-
A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch block
is referred to as protected code, and the syntax for using try/catch looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionName e1)
{
// Catch block
}The code which is prone to exceptions is placed in the try block. When an exception occurs, that
exception occurred is handled by catch block associated with it. Every try block should be
immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If
the type of exception that occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.
Example
The following is an array declared with 2 elements. Then the code tries to access the 3rd element
of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");}}
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Creating user defined exception
In java we have already defined, exception classes such as ArithmeticException,
NullPointerException etc. These exceptions are already set to trigger on pre-defined conditions
such as when you divide a number by zero it triggers
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);
}}
class TestCustomException1{
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...");
} }
Out put
Compile by: javac TestCustomException1.java
tomException1.java:3: error: cannot find symbol
static void validate(int age)throwsInvalidAgeException{
^
symbol: class InvalidAgeException
location: class TestCustomException1
tomException1.java:5: error: cannot find symbol
throw new InvalidAgeException("not valid");
^
symbol: class InvalidAgeException
location: class TestCustomException1
2 errors
User Define Exception(Custom Define Exception)//checked Exception or compile
class UnderAgeException extends Exception{
UnderAgeException(){
super(“you are underage”);}
UnderAgeException(String message){
super(message)}}
class voting{
public static void main(String[]args){
int age=16;
try{
if(age<18){
throw new UnderAgeException(“you cannot vote as your age is below 18”);
}
else{
System.out.println(“you can vote now…!!!”);}}
catch(UnderAgeException e){
e.printStackTrace();
}System.out.println("hello");}}
User Define Exception(Custom Define Exception)//unchecked Exception or Runtime
class UnderAgeException extends Runtime Exception{
UnderAgeException(){
super(“you are underage”);}
UnderAgeException(String message){
super(message)}}
class voting{
public static void main(String[]args){
int age=16;
try{
if(age<18){
throw new UnderAgeException(“you cannot vote as your age is below 18”);
}
else{
System.out.println(“you can vote now…!!!”);}}
catch(UnderAgeException e){
e.printStackTrace();
}System.out.println("hello");
}}
import java.io.*;
class exception
{
public static void main(String args[])
{
int no;
int a[]=new int[2];
DataInputStream cin=new DataInputStream(System.in);
try
{
System.out.print("Enter any no");
no=Integer.parseInt(cin.readLine());
int r=10/no;
a[no]=50;
System.out.println("r="+r+"arr="+a[no]);
}
catch(ArithmeticException e)
{
System.out.println("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index error");
}
catch(IOException e)
{
System.out.println("wrong input");
}
catch(NumberFormatException e)
{
System.out.println("wrong input");
}
finally
{
System.out.println("finally block");
}}}