Exception Handling
Exception Handling
Exception Handling
Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such exceptions to
prevent abrupt termination of program. The term exception means exceptional condition, it is a problem that
may arise during the execution of program. A bunch of things can lead to exceptions, including programmer
error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc.
Exception
A Java Exception is an object that describes the exception that occurs in a program. When an exceptional
events occurs in java, an exception is said to be thrown. The code that's responsible for doing something about
the exception is called an exception handler.
Exception class is for exceptional conditions that program should catch. This class is extended to
create user specific exception classes.
Runtime Exception is a subclass of Exception. Exceptions under this class are automatically defined
for programs.
Checked Exception
The exception that can be predicted by the programmer.Example : File that need to be opened is not found.
These type of exceptions must be checked at compile time.
Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at
compile time. Example : ArithmeticException, NullPointerException, Array Index out of Bound
exception. Unchecked exceptions are checked at runtime.
Error
Errors are typically ignored in code because you can rarely do anything about an error. Example : if stack
overflow occurs, an error will arise. This type of error is not possible handle in code.
Uncaught Exceptions
When we don't handle the exceptions, they lead to unexpected program termination. Lets take an example for
better understanding.
class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a;
}
}
This will lead to an exception at runtime, hence the Java run-time system will construct an exception and then
throw it. As we don't have any mechanism for handling exception in the above program, hence the default
handler will handle the exception and will print the details of the exception on the terminal.
try
2.
catch
3.
throw
4.
throws
5.
finally
Exception handling is done by transferring the execution of a program to an appropriate exception handler
when exception occurs.
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
Output
Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero inside try block. The
program control is transfered outside try block. Thus the line "This line will not be executed" is never parsed
by the compiler. The exception thrown is handle in catch block. Once the exception is handled the program
controls continue with the next line in the program. Thus the line "After exception is handled" is printed.
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}
Output
divide by zero
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(Exception e)
{
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
{
System.out.println("array index out of bound exception");
}
}
}
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x=arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}
If you do not explicitly use the try catch blocks in your program, java will provide a default exception
handler, which will print the exception details on the terminal, whenever exception occurs.
2.
Super class Throwable overrides toString() function, to display error message in form of string.
3.
While using multiple catch block, always make sure that exception subclasses comes before any of
their super classes. Else you will get compile time error.
4.
In nested try catch, the inner try block, uses its own catch block as well as catch block of the outer try,
if required.
5.
Syntax
try(resource-specification)
{
//use the resource
}catch()
{...
}
This try statement contains a paranthesis in which one or more resources is declare. Any object that
implements java.lang.AutoCloseable or java.io.Closeable, can be passed as a parameter to try statement. A
resource is an object that is used in program and must be closed after the program is finished. The try-withresources statement ensures that each resource is closed at the end of the statement, you do not have to
explicitly close the resources.
while((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
}catch(IOException ie)
{ System.out.println("exception"); }
}
}
NOTE: In the above example, we do not need to explicitly call close () method to close BufferedReader
stream.
Throw Keyword
throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can
be thrown. Program execution stops on encountering throw statement, and the closest catch statement is
checked for matching type of exception.
Syntax
throw ThrowableInstance
2.
New NullPointerException("test");
This constructs an instance of NullPointerException with name test.
throws Keyword
Any method capable of causing exceptions must list all the exceptions possible during its execution, so that
anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by
using the throws keyword.
Syntax
NOTE :
It is necessary for all exceptions, except the exceptions of type Error and RuntimeException, or any of their
subclass.
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code always
executes whether or not exception has occurred. Using a finally block, lets you run any cleanup type
statements that you want to execute, no matter what happens in the protected code. A finally block appears at
the end of catch block
finally
{
System.out.println("finally is always executed.");
}
}
}
Output
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound exception.
You can see in above example even if exception is thrown by the program, which is not handled by catch
block, still finally block will get executed.
class Test
{
static void sum(int a,int b) throws MyException
{
if(a<0)
{
throw new MyException(a);
}
else
{
System.out.println(a+b);
}
}
}
}
}
Points to Remember
1.
2.
You don't have to implement anything inside it, no methods are required.
3.
4.