Object Oriented Programming Using Java 22MCA22
MODULE 4
EXCEPTION HANDLING
The exception hierarchy:
• An exception is an error that occurs at run time.
• In java, all exceptions are represented by classes.
• All exception class are derived from a class called Throwable.
• Throwable class is the superclass of all errors and exceptions in the Java language.
• When an exception occurs in a program, an object of some type of exception class is
generated.
Benefits of exception handling
• By using exceptions to manage errors, Java programs have the following
advantages over traditional error management techniques:
• 1: Separating Error Handling Code from
• "Regular" Code.
• 2: Propagating Errors Up the Call Stack.
• 3: Grouping Error Types and Error Differentiation.
Exception handling fundamentals
• Java exception handling is managed via five keywords.
• They are try, catch, throw, throws and finally.
• Programs statements that you want to monitor for exceptions are contained a try
block.
• If an exception occurs within the try block, it is thrown.
• Your code can catch this exception using catch and handle it in some rational manner.
• System-generated exceptions are automatically thrown by the java run-time system.
• To manually throw an exception, use the keyword throw.
• Java try block must be followed by either catch or finally block.
• In some cases, an exception that is thrown out of a method must be specified as such
by a throws clause.
• Any code that absolutely must be executed upon exiting from a try block is put in a
finally block.
Syntax of java try-catch
try {
//code that may throw exception
}
catch(Exception_class_Name ref)
{
//code to handle exception
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 1
Object Oriented Programming Using Java 22MCA22
Syntax of try-finally block
try {
//code that may throw exception
}
finally
{
}
Ex:
Without using try-catch
public class testtry
{
public static void main(String args[]) {
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Output:
• Exception in thread main java.lang.ArithmeticException:/ by zero
Using java try-catch block.
public class testtry1 {
public static void main(String args[]) {
try{
int data=50/0;
}
catch(ArithmeticException e) {
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
Output:
• Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...
EX:
public class testtry2 {
public static void main(String args[]) {
int[] nums = new int[4];
try{
System.out.println(“RNSIT”);
nums[7]=80;
System.out.println(“MCA”);
}
catch(ArithmeticException e) {
System.out.println(e);
}
System.out.println("rest of the code...");
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 2
Object Oriented Programming Using Java 22MCA22
}
}
The consequences of an uncaught exception
• If your program does not catch an exception, then it will be caught by the JVM.
• The trouble is that the JVM’s default exception handler terminates execution and
displays an error message followed by a list of the methods calls that lead to the
exception.
Internal working of java try-catch block
Using multiple catch clauses
• You can associate more than one catch clause with a try. Each catch must catch a
different type of exception.
• At a time only one Exception is occurred and at a time only one catch block is
executed.
• Ex:
public class MultipleCatchBlock1 {
public static void main(String args[]) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
System.out.println("task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("task 2 completed"); }
catch(Exception e) {
System.out.println("common task completed"); }
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 3
Object Oriented Programming Using Java 22MCA22
System.out.println("rest of the code...");
}
}
• All catch blocks must be ordered from most specific to most general
i.e. Exception class have to come at last.
class TestMultipleCatchBlock1{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30;
}
catch(Exception e){
System.out.println("common task completed");
}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 c ompleted");
}
System.out.println("rest of the code...");
}
}
OUTPUT
Compile-time error
Catching subclass exceptions
• There is one important point about multiple catch clauses that relates to subclasses.
• A catch clause for a superclass will also match any of its subclasses.
• If you want to catch exceptions of both a superclass type and a subclass type, put the
subclass first in the catch sequence.
• if you do not, then superclass catch will also catch all derived classes.
class ExcDemo5 {
public static void main(String[] args) {
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.length; i++) {
try {
System.out.println(numer[i] + " / " + denom[i] + " is " +
numer[i]/denom[i]);
}catch (ArrayIndexOutOfBoundsException exc){
System.out.println("No matching element found.");
}
catch (Exception e){
System.out.println("Some exception occurred.");
}
}
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 4
Object Oriented Programming Using Java 22MCA22
}
}
try blocks can be nested
• One try block can be nested within another.
• An exception generated within the inner try block that is not caught by a catch
associated with that try is propagated to the outer try block.
Syntax
try
{
statements ;
try
{
statements;
}
catch(Exception e) { }
}
catch(Exception e) { }
....
Ex:
public class Excep6 {
public static void main(String args[]) {
try {
try {
int a[]=new int[5]; a[5]=30;
}
catch(Exception e) {
System.out.println("task1 is completed");
}
try {
int a[]=new int[5];
a[4]=30/0;
}
catch(ArithmeticException e) {
System.out.println("task2 is completed");
}
int b[]=new int[5];
b[5]=30;
}
catch(Exception e) {
System.out.println("task3 is completed");
}
}
}
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 5
Object Oriented Programming Using Java 22MCA22
Throwing an 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 syntax of java throw keyword is given below throw exceptob;
• Here, exceptob must be an object of an exception class derived from Throwable.
• Only object of Throwable class or its sub classes can be thrown.
Creating Instance of Throwable class
• There are two possible ways to get an instance of class Throwable,
• Using a parameter in catch block.
• Creating instance with new operator.
new NullPointerException("test");
• This constructs an instance of NullPointerException with name test.
Ex: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 thread main java.lang.ArithmeticException:not valid
Ex:2
class Test21{
static void avg() {
try {
throw new ArithmeticException("demo");
}
catch(Exception e) {
System.out.println(e);
}
}
public static void main(String args[]) {
avg();
System.out.println("Exception caught");
}
}
throws
• In some cases, if a method generates an exception that it does not handle, it must declare
that exception in a throws clause.
• The general form of throws is
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 6
Object Oriented Programming Using Java 22MCA22
return-type methName(param-list)throws except-list {
//body
}
• Here, except-list is a comma-separated list of exceptions that the method might throw
outside of itself.
• subclass of Error or RuntimeException don’t need to be specified in a throws list.
Ex:1
import java.io.*;
class rns {
void mca()throws IOException {
throw new IOException("device error");
}
}
public class Testthrows2 {
public static void main(String args[]) {
try{
rns m=new rns(); m.mca();
}
catch(Exception e) {
System.out.println(e);
System.out.println("normal flow...");
}
}
}
EX:2
import java.io.*;
class rnsit{
void mca(int a) throws IOException,ArithmeticException{
if(a%2==0)
throw new IOException("device error");
else
throw new ArithmeticException("error");
}
}
class Testthrows {
public static void main(String args[]) {
try{
rnsit m=new rnsit(); m.mca(2);
}
catch(Exception e){
System.out.println(e); }
System.out.println("normal flow...");
}
}
OUTPUT
java.io.IOException:device Error normal flow…
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 7
Object Oriented Programming Using Java 22MCA22
EX3:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne(); }
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Output
inside throwOne
caught java.lang.IllegalAccessException: demo
Difference between throw and throws
A close look at Throwable
• All exception types are subclasses of the built-in class Throwable.
• Throwable is at the top of the exception class hierarchy.
• Immediately below Throwable are two subclasses that partition exceptions into two
distinct branches.
• One branch is headed by Exception.
• This class is used for exceptional conditions that user programs should catch.
• This is also the class that you will subclass to create your own custom exception
types.
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 8
Object Oriented Programming Using Java 22MCA22
• The other branch is topped by Error, which defines exceptions that are not
expected to be caught under normal circumstances by your program.
•
Methods defined by throwable
Exception hierarchy
• The class at the top of the exception class hierarchy is the Throwable class, which is
a direct subclass of the Object class.
• Throwable has two direct subclasses –
1. Exception
2. Error
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 9
Object Oriented Programming Using Java 22MCA22
Throwable class:
• Throwable class which is derived from Object class, is a top of exception hierarchy
from which all exception classes are derived directly or indirectly.
• It is the root of all exception classes.
• It is present in java.lang package.
Error:
• Error class is the subclass of Throwable class and a superclass of all the runtime error
classes.
• It terminates the program if there is problem-related to a system or resources (JVM).
Exception:
• It is represented by an Exception class that represents errors caused by the program
and by
• external factors.
• Exception class is a subclass of Throwable class and a superclass of all the exception
classes.
• All the exception classes are derived directly or indirectly from the Exception class.
• They originate from within the application.
•
Exception Class Hierarchy in Java
Using finally
• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block must be followed by try or catch block.
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 10
Object Oriented Programming Using Java 22MCA22
Syntax:
finally{
finally code
}
Ex:1
class TestFinallyBlock {
public static void main(String args[]) {
try{
I nt data=25/5; System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);} finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Ex:2
class TestFinallyBlock1 {
public static void main(String args[]) {
try {
int data=25/0; System.out.println(data);
}
catch(NullPointerException e) {
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
• OUTPUT
(finally block is always executed)
Exception in thread main
java.lang.ArithmeticException:/ by zero
For each try block there can be zero or more catch blocks, but only one finally block.
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 11
Object Oriented Programming Using Java 22MCA22
Difference between final, finally and finalize
Classification or Types of exceptions
• Exceptions can be categorized into two ways:
• Built-in Exceptions
o Checked Exception
o Unchecked Exception
• User-Defined Exceptions
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 12
Object Oriented Programming Using Java 22MCA22
Built-in exceptions
• Exceptions that are already available in Java libraries are referred to as built-in
exception.
• These exceptions are able to define the error situation so that we can understand the
reason of getting this error.
• It can be categorized into two broad categories, i.e., checked exceptions and
unchecked exception.
Checked Exception
• Checked exceptions are called compiletime exceptions because these exceptions are
checked at compile-time by the compiler.
• The compiler ensures whether the programmer handles the exception or not.
• The programmer should have to handle the exception; otherwise, the system has
shown a compilation error.
Checked exceptions defined by java.lang
UnChecked Exception
• An unchecked exception is an exception that occurs at the time of execution.
• These are also called as Runtime Exceptions.
• These include programming bugs, such as logic errors or improper use of an API.
• Runtime exceptions are ignored at the time of compilation.
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 13
Object Oriented Programming Using Java 22MCA22
Unchecked exceptions defined by java.lang
Creating Exception subclasses or how to create your own
exception
• If you are creating your own Exception that is known as custom exception or user-
defined exception.
• Just define a subclass of Exception(which is a subclass of Throwable).
• The Exception class does not define any methods of its own. It does inherit those
methods provided by Throwable.
• You can override one or more of these methods in exception subclass that you
create.
• Two commonly used Exception constructors are shown here;
Exception()
Exception(String msg)
Ex:
class MyException extends Exception {
private int detail; MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]"; }
}
public class rnsitown {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if (a > 10)
{
throw new MyException(a);
}
System.out.println("Normal exit");
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 14
Object Oriented Programming Using Java 22MCA22
}
public static void main(String args[] {
try {
compute(1); compute(20);
}
catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
Output
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
• If you want to represent any object as a string, toString() method comes into existence.
• The toString() method returns the string representation of the object.
Chained Exceptions
• Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception.
• For example, consider a situation in which a method throws an ArithmeticException
because of an attempt to divide by zero but the actual cause of exception was an I/O
error which caused the divisor to be zero.
• The method will throw only ArithmeticException to the caller.
• So the caller would not come to know about the actual cause of exception.
Chained Exception is used in such type of situations.
• Constructors Of Throwable class Which support chained exceptions in java :
• Throwable(Throwable cause) :- Where cause is the exception that causes the current
exception.
• Throwable(String msg, Throwable cause) :- Where msg is the exception message
and cause is the exception that causes the current exception.
• Methods Of Throwable class Which support chained exceptions in java :
• getCause() method :- This method returns actualcause of an exception.
• initCause(Throwable cause) method :- This method sets the cause for the calling
exception.
public class chain {
public static void main(String[] args)
{
try {
NumberFormatException ex = new
NumberFormatException("Exception");
ex.initCause(new NullPointerException("This is actual cause of the
exception"));
throw ex;
}
catch(NumberFormatException a) {
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 15
Object Oriented Programming Using Java 22MCA22
System.out.println(a);
System.out.println(a.getCause());
}
}
}
Output
java.lang.NumberFormatException: Exception java.lang.NullPointerException: This is actual
cause of the exception
Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 16