Java Module 4
Java Module 4
Java Module 4
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.
Page 1
Object Oriented Programming Using Java 22MCA22
}
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
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(“RNSI
T”);
nums[7]=80;
System.out.println(“MCA”);
}
catch(ArithmeticException e)
{System.out.println(e);
}
System.out.println("rest of the code...");
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.
Page 3
Object Oriented Programming Using Java 22MCA22
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
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.");
}
}
Page 4
Object Oriented Programming Using Java 22MCA22
}
}
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");
}
}
}
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
Page 6
Object Oriented Programming Using Java 22MCA22
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…
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
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
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.
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.
Page 11
Object Oriented Programming Using Java 22MCA22
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.
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.
Page 13
Object Oriented Programming Using Java 22MCA22
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.
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
Page 16