0% found this document useful (0 votes)
8 views41 pages

Unit-2 Exception Handling

The document discusses exception handling in Java, categorizing errors into compile-time and run-time errors. It explains the importance of handling exceptions to maintain program flow and outlines the general structure of exception handling code using try, catch, and finally blocks. Additionally, it describes different types of exceptions, including checked, unchecked, and errors, along with methods for managing exceptions effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views41 pages

Unit-2 Exception Handling

The document discusses exception handling in Java, categorizing errors into compile-time and run-time errors. It explains the importance of handling exceptions to maintain program flow and outlines the general structure of exception handling code using try, catch, and finally blocks. Additionally, it describes different types of exceptions, including checked, unchecked, and errors, along with methods for managing exceptions effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

IMS Engineering College

NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.


Tel: (0120) 4940000
Department: Computer Science and Engineering

UNIT – 2
EXCEPTION HANDLING

Types of Errors:
Errors may broadly be classified in to two categories.
❖ Compile time error
❖ Run time error

Compile Time Error:


All syntax errors detected and displayed by the Java compiler are termed as Compile-
time errors. If the compiler detects an error while compiling a program, then the .class
file will not be created. For successful compilation we have to correct the syntax error
first.
class Calculate
{
int cube(int x)
{
return x*x*x
}

public static void main(String args[])


{
int result=cube(5);
System.out.println(result);
}
}
While compiling the above program Calculate.java, the following message will be
displayed on the screen:

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Some of the most common compile-time errors are:


❖ Use of variable without declaration
❖ Missing brackets in classes and methods
❖ Missing semicolons
❖ Incompatible assignment statements
❖ Bad references of objects and do on.

Run Time Error:


Sometimes, a program may compile successfully creating .class file but may not execute
properly i.e., they may produce wrong result or may terminate abruptly. These errors
may
occur due to wrong logic of the program and many more reasons like
❖ Dividing an integer by zero
❖ Accessing an element that is out of bounds of an array
❖ Converting invalid strings to number
❖ Trying to store a value into an array of incompatible class or type etc.
Such types of errors are termed as Run-time errors.
Let us consider the following example for the demonstration of run-time error:
class Runer
{
int divi(int a, int b)
{
int c= a/b;
return(c);
}

public static void main(String args[])


SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

{
Runer r = new Runer();
int result=r.divi(5,0);
System.out.println(result);
}
}

When we compile the above program, then it will create the .class file as the compilation
is successful. The compiler will not display any error message as there is no syntax error
in the code.
When we try to run the program then it will display the error condition which causes the
program to stop after displaying the appropriate message.
Exceptions : Exception is a condition that is caused by run time error in the program.
Or
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of execution or an abnormal condition that disrupts Normal program flow.
When the Java interpreter encounters an error such as dividing an integer by zero, it
creates an exception object and throws it (i.e., informs us that an error has occurred).

If the exception object is not caught and handled properly, the interpreter will display an
error message and will terminate the program.

If we want the program to continue with the execution of remaining code then we should try
to catch the exception object thrown by error condition and then display an error message
for taking corrective actions. This task is known as exception handling.
The purpose of exception handing mechanism is to provide a means to detect and report an
“exceptional circumstance” so that appropriate action can be taken.

The mechanism suggests incorporation of a separate error handling code that performs the
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information ( Catch the exception)
4. Take corrective actions (Handle the exception)

The error handling code basically consists of two segments , one to detect errors and to
throw exceptions and the other to catch exceptions and to take appropriate actions.

There are many cases where abnormal conditions happen during program execution,
such as:
❖ Trying to access an out - of –bounds array elements.
❖ The file we try to open may not exist.
❖ The file we want to load may be missing or in the wrong format.
❖ The other end of our network connection may be non –existence.
❖ If these cases are not prevented or at least handled properly, either the program will
be aborted abruptly, or the incorrect results or status will be produced.
❖ When an error occurs with in the java method, the method creates an exception
object and hands it off to the runtime system.
❖ The exception object contains information about the exception including its type and
the state of the program when the error occurred. The runtime system is then
responsible for finding some code to handle the error.
❖ In java creating an exception object and handling it to the runtime system is called
throwing an exception.
❖ Exception is an object that is describes an exceptional ( i.e. error) condition that has
occurred in a piece of code at run time.
❖ When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error. That method may choose to
handle the exception itself, or pass it on. Either way, at some point, the exception is
caught and processed.
❖ Exceptions can be generated by the Java run-time system, or they can be manually
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

generated by our code.


❖ System generated exceptions are automatically thrown by the Java runtime system.

These exceptions are caused by user error, programmer error, and physical resources.Based
on these, the exceptions can be classified into three categories.
• Checked exceptions − A checked exception is an exception that occurs at the
compile time, also called as compile time (static time) exceptions. These
exceptions cannot be ignored at the time of compilation. So, the programmer
should handle these exceptions.
• Unchecked exceptions − An unchecked exception is an exception that occurs at
run time, also called as Runtime Exceptions. These include programming bugs,
such aslogic errors or improper use of an API. Runtime exceptions are ignored at
the time ofcompilation.
• Errors − Errors are not exceptions, but problems may arise beyond the control of
theuser or the programmer. Errors are typically ignored in our code because we
can rarely do anything about an error. For example, if a stack overflow occurs, an
error will arise. They are also ignored at the time of compilation.

• Error: An Error indicates serious problem that a reasonable application should


not
try to catch.
• Exception: Exception indicates conditions that a reasonable application might try
to
catch.

General form of Exception Handling code:

try
{

// block of code to monitor for errors


}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

{
// block of code to be executed before try block ends
}

Exception hierarchy

The java.lang.Exception class is the base class for all exception classes.
All exception types are subclasses of the built-in class Throwable. Thus, 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 we will subclass to create our
own custom exception types.
There is an important subclass of Exception, called RuntimeException. Exceptions of this
type are automatically defined for the programs that we write and include things such as
division by zero and invalid array indexing.
The other branch is topped by Error, which defines exceptions that are not expected to be
caught under normal circumstances by our program. Exceptions of type Error are used by
the Java run-time system to indicate errors having to do with the run-time environment,
itself. Stack overflow is an example of such an error.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Exceptions Methods
Method Description
public String getMessage() Returns a detailed message about the exception that
has occurred. This message is initialized in the
Throwable constructor.
public Throwable getCause() Returns the cause of the exception as represented by
aThrowable object.
public String toString() Returns the name of the class concatenated with the
re-sult of getMessage().
public void printStackTrace() Prints the result of toString() along with the stack trace
toSystem.err, the error output stream.
public StackTraceElement Returns an array containing each element on the stack
trace. The element at index 0 represents the top of the
[]getStackTrace()
call stack, and the last element in the array represents
themethod at the bottom of the call stack.
public Fills the stack trace of this Throwable object with the
current stack trace, adding to any previous information
Throwable
in the stack trace.
fillInStackTrace(
)

Exception handling in java uses the following Keywords


1. try
2. catch
3. finally
4. throw
5. throws

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Throwing and catching the exception

1. The try/catch block is used as follows:

try
{
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
Java uses the keyword try to preface a block of a code that is likely to cause an error
condition and “throw” an exception. A catch block defined by the keyword catch “catches
“ the exception thrown by the try block and handles it appropriately.
The try block can have one more than one statement that could generate an exception. If nay
one statement generates an exception the remaining code in the block are skipped and
execution jumps to the catch block that is placed next to the try block.
The catch block can also have more than one statements that are necessary to process the
exception.
A catch statement involves declaring the type of exception that might be tried to catch.
If an exception occurs, then the catch block (or blocks) which follow the try block is
checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to
the catch block similar to an argument that is passed into a method parameter.
To illustrate the try-catch blocks the following program is developed.
class Erex2
{
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

public static void main(String args[])


{
int a = 10;
int b= 5;
int c =5;
int x,y;
try

{
x= a/(b-c);
System.out.println(“x=”+x);
}
catch (ArithmeticException e)
{

System.out.println(“Division by zero.”);
}

y= a/(b+c);
system.out.println(“y=.”+y);
}
}
Output:

Catching command line arguments


class Errex3
{
public static void main(String args[])
{
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

int i=0;
int n, count=0;
for( int j=0;j<args.length;j++)
{
try
{
n= Integer.parseInt(args[j]);
}
catch(NumberFormatException e)
{
i=i+1;
System.out.println("invalid number="+args[j]);
continue;
}
count=count+1;
}
System.out.println("valid number="+count);
System.out.println("Invalid number="+i);

}
}

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Multiple catch Clauses


In some cases, more than one exception could be raised by a single piece of code. To handle
this multiple exceptions, two or more catch clauses can be specified.
Here, each catchblock catches different type of exception. When an exception is thrown,
each catch statementis inspected in order, and the first one whose type matches that of the
exception is executed. After one catch statement executes, the others are skipped, and
execution continues after thetry/catch block. The following example traps two different
exception types:

public class Errex4

public static void main(String args[])

try

int a[] = new int[10];

int b = a[11]/0;

catch(ArithmeticException e)

System.out.println(e.getMessage());

catch(ArrayIndexOutOfBoundsException e)

System.out.println(e.getMessage());

catch(Exception e)

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println(e.getMessage());

} .

While the multiple catch statements is used, it is important to remember that exception
subclasses must come before their super classes. A catch statement which uses a superclass
will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never
be reached if it came after its superclass. And also, in Java, unreachable code is an error.
Forexample, consider the following program:
class MultiCatch_Example
{
public static void main(String args[])
{
try
{
int a,b;
a = args.length;
System.out.println(“a = “ + a);
b = 10 / a; //may cause division-by-zero
errorint arr[] = { 10,20 };

c[5] =100;
}
catch(Exception e)

{
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println(“Generic Exception catch.”);


}
catch(ArithmeticException e)
{
System.out.println(“Divide by 0: “ + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index oob: “ + e);
}
System.out.println(“After try/catch blocks.”);
}
}
The exceptions such as ArithmeticException, and ArrayIndexOutOfBoundsException are
the subclasses of Exception class. The catch statement after the base class catch statement
israising the unreachable code exception.

Nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}

catch(Exception e)
{
}

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
catch(Exception e)
{
}
....

The following program is an example for Nested try statements.


class Nestedtry_Example{
public static void main(String args[]){
try
{
try

System.out.println(“division”);
int a,b;
a=0;
b =10/a;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new
int[5];

a[6]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{

System.out.println(e);

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
System.out.println(“other statement);
}
catch(Exception e)
{
System.out.println(“handeled”);}
System.out.println(“normal flow..”);
}
}

The Finally Block


The finally statement that can be used to handle an exception that is not caught buy any of
the previous catch statements. The finally block may be added after the try block or after
the last catch block. A finally block of code always executes, irrespective of the occurrence
of an Exception. We can use it to perform certain house-keeping operations such as closing
files and releasing system resources. A finally block appears at the end of the catch blocks
that follows the below syntax.
Syntax
try
{
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
finally
{
// The finally block always executes.
}

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Example
public class Errex5
{
public static void main(String args[])
{
try
{
int a,b;
a=0;
b=10/a;
}
catch(ArithmeticException e)
{
System.out.println("Exception thrown :" + e);
}
finally
{
System.out.println("The finally block is executed");
}
}
}

Points to remember:
• A catch clause cannot exist without a try statement.
• It is not compulsory to have finally clauses whenever a try/catch block is present.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

• The try block cannot be present without either catch clause or finally clause.
• Any code cannot be present in between the try, catch, finally blocks.

Throwing our own exceptions

Throw keyword
The Java throw keyword is used to explicitly throw an exception. The general form of
throw is shown below:
throw ThrowableInstance;
or
throw new Throwable_subclass
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throw-
able.
Primitive types, such as int or char, as well as non-Throwable classes, such as String and
Object, cannot be used as exceptions.
There are two ways to obtain a Throwable object:
1. using a parameter in a catch clause
2. creating one with the new operator.

The following program explains the use of throw keyword.


import java.util.Scanner;
public class TestThrow
{
static void validate(int age)
{
try
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
catch(ArithmeticException e)
{
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println("Caught inside ArithmeticExceptions.");


throw e; // rethrow the exception
}
}
public static void main(String args[])
{
System.out.println("Enter age");
Scanner s = new Scanner(System.in);
int age= s.nextInt();
try
{
validate(age);
}
catch(ArithmeticException e)
{
System.out.println("ReCaught ArithmeticExceptions.");
}
}
}

The flow of execution stops immediately after the throw statement and any subsequent
statements that are not executed. The nearest enclosing try block is inspected to see if it
has a catch statement that matches the type of exception. If it does find a match, control
is trans-ferred to that statement. If not, then the next enclosing try statement is inspected,
and so on. If no matching catch is found, then the default exception handler halts the
program and printsthe stack trace.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

The Throws/Throw Keywords

If a method does not handle a checked exception, the method must be declared using
the throws keyword. The throws keyword appears at the end of a method’s signature.
The difference between throws and throw keywords is that, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.
The following method declares that it throws a Remote Exception −
Example
import java.io.*;
public class throw_Example1
{
public void function(int a) throws RemoteException
{
// Method implementation throw new RemoteException();

} // Remainder of class definition


}
A method can declare that it throws more than one exception, in which case the excep-
tions are declared in a list separated by commas. For example, the following method
declaresthat it throws a RemoteException and an ArithmeticException −
import java.io.*;
public class throw_Example2 {
public void function(int a) throws RemoteException,ArithmeticException
{
// Method implementation
}
// Remainder of class definition
}

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

BUILT-IN EXCEPTIONS
Built-in exceptions are the exceptions which are available in Java libraries. These excep-
tions are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.

Exceptions Description
Arithmetic Exception It is thrown when an exceptional condition has oc-curred
in an arithmetic operation.
ArrayIndexOutOfBound It is thrown to indicate that an array has been accessedwith
Exception an illegal index. The index is either negative or greater than
or equal to the size of the array.
ClassNotFoundException This Exception is raised when we try to access a classwhose
definition is not found.
FileNotFoundException This Exception is raised when a file is not accessible
or does not open.
IOException It is thrown when an input-output operation failed or
interrupted.
InterruptedException It is thrown when a thread is waiting, sleeping, or do-ing
some processing, and it is interrupted.
NoSuchFieldException It is thrown when a class does not contain the field (or
variable) specified.
NoSuchMethodException It is thrown when accessing a method which is notfound.

NullPointerException This exception is raised when referring to the membersof a


null object. Null represents nothing.
NumberFormatException This exception is raised when a method could not con-vert a
string into a numeric format.
RuntimeException This represents any exception which occurs during
runtime.
StringIndexOutOfBoundsEx- It is thrown by String class methods to indicate that anindex
ception is either negative than the size of the string

The following Java program explains NumberFormatException


class NumberFormat_Example
{
public static void main(String args[])
{
try
{
int num = Integer.parseInt (“hello”) ;
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

System.out.println(num);
}
catch(NumberFormatException e)

System.out.println(“Number format exception”);


}
}
}
The following Java program explains StackOverflowError exception.
class Example
{
public static void main(String[] args)
{
fun1();
}

public static void fun1()


{
fun2();
}
public static void fun2()
{
fun1();
}
}
Output:
Exception in thread “main”
java.lang.StackOverflowErrorat
Example.fun2(File.java:14)
at Example.fun1(File.java:10)

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Checked and Unchecked Exceptions in Java


There are two types of exceptions in Java:
• first is predefined exceptions,
• second user-defined exceptions.
The predefined exceptions are those exceptions that are already defined by the java system.
All the predefined exceptions are further divided into two groups:
1. Checked Exceptions
2. Unchecked Exceptions

Checked Exceptions in Java

Checked exceptions are those exceptions that are checked by the java compiler itself at
compilation time and are not under runtime exception class hierarchy.
If a method throws a checked exception in a program, the method must either handle the
exception or pass it to a caller method.
We must handle checked exceptions either by using try and catch block or by using a throws
clause in the method declaration. If not handles properly, it will give a compile-time error.
Some exceptions are detected at compile-time and some other at runtime.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

The exceptions that are checked by Java compiler at compilation time is called checked
exception in Java. All the exceptions except RuntimeException, Error, and their subclasses
are checked exceptions.

Note:
Compile-time errors are not exceptions. They come under errors. In Java, only runtime
errors come under exceptions.
List of Checked Exceptions in Java

A list of some important checked exceptions is given below:


▪ ClassNotFoundException
▪ InterruptedException
▪ InstantiationException
▪ IOException
▪ SQLException
▪ IllegalAccessException
▪ FileNotFoundException, etc
Example-1
public class CheckedExceptionEx1
{
public static void main(String[] args)
{
System.out.println("Hello Java");
Thread.sleep(1000); // Here, main thread paused for a specified amount of time. //
Compilation error.
}
}

Handle Checked Exception in Java

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

To avoid this compilation error, we will have to handle this checked exception either using
a try-catch block or throws clause.
Handle Checked Exception in Java

To avoid this compilation error, we will have to handle this checked exception either using
a try-catch block or throws clause. Let’s handle it and see what will be the output?
Example 2:
public class CheckedExceptionEx1
{
public static void main(String[] args)
{
System.out.println("Hello Java");
// Apply the try-catch block to handle checked exception.
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}

Example program in which we will handle Java checked exceptions using a throws clause.
Program code 3:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class CheckedExceptionEx

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

{
public static void main(String[] args) throws FileNotFoundException
{
// Creating a file object.
File file = new File("not_existing_file.txt");

// Create an object of FileInputStream and pass reference variable file to it.


FileInputStream stream = new FileInputStream(file);
}
}

Unchecked Exceptions (Runtime Exceptions) in Java

Unchecked exceptions in Java are those exceptions that are checked by JVM, not by java
compiler. They occur during the runtime of a program.
All exceptions under the runtime exception class are called unchecked exceptions or runtime
exceptions in Java.
We can write a Java program and compile it. But we cannot see the effect of unchecked
exceptions and errors until we run the program.
This is because Java compiler allows us to write a Java program without handling unchecked
exceptions and errors.
Java compiler does not check runtime exception at compile time whether programmer
handles them or not.
If a runtime exception occurs in a method and the programmer does not handle it, JVM
terminates the program without the execution of rest of the code.
List of Unchecked Exceptions in Java

Some important examples of runtime exceptions are given below:


▪ ArithmeticException
▪ ClassCastException
▪ NullPointerException
▪ ArrayIndexOutOfBoundsException
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

▪ NegativeArraySizeException
▪ ArrayStoreException
▪ IllegalThreadStateException
▪ SecurityException, etc.

Program code 4:
public class UncheckedExceptionEx1 {
public static void main(String[ ] args)
{
int x = 10;
int y = 0;
int z = x/y; // runtime exception occurs.
System.out.println(z);
}
}
Handle Runtime Exception in Java

To avoid this runtime error, we will have to handle this unchecked exception either using a
try-catch block or throws clause.
Program code 5:
public class HandleRuntimeException {
public static void main(String[] args)
{
int x = 10;
int y = 0;
// Apply try-catch block to handle runtime exception.
try {
int z = x/y; // runtime exception.
System.out.println(z);
} catch(ArithmeticException ae)
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

{
System.out.println("A number cannot be divided by zero");
}
}
}

Program code 6:
public class UncheckedExceptionEx2 {
public static void main(String[] args)
{
int x[ ] = {1, 2, 3, 4};
/* Here, an array contains only 4 elements, but we will try to * display the value of 6th
element.
It should throw ArrayIndexOutOfBoundsException */
System.out.println(x[6]);
}
}
Difference between Checked and Unchecked Exceptions in Java

There are many important differences between checked and unchecked exceptions in java.
They are as follows:
1. The classes that directly inherit Throwable class except RuntimeException and Error are
called checked exceptions whereas, classes that directly inherit RuntimeException are
called unchecked exceptions.
2. Checked exceptions are checked and handled at compile-time whereas, unchecked
exceptions are not checked and handled at compile time. They are checked at runtime.
3. Examples of checked exceptions are IOException, SQLException,
ClassNotFoundException, etc whereas, examples of unchecked exceptions are
ArithmeticException, ClassCastException, NullPointerException,
IllegalArgumentException, etc.
4. When a checked exception occurs in a method, the method must either catch the
exception or pass exception to its caller method. But in the case of an unchecked
exception, Java compiler does not force to catch exception or to declare it in a throws
clause.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

5. Checked exceptions in java extends Exception class, whereas unchecked exceptions


extends RuntimeException class.
6. A checked exception happens when there is a chance of a higher failure rate. whereas
unchecked exceptions occur, mostly due to programming mistakes/errors.

Throw Keyword in Java | Java Throw Exception


Throw in Java is a keyword that is used to throw a built-in exception or a custom exception
explicitly or manually. Using throw keyword, we can throw either checked or unchecked
exceptions in Java programming.
When an exception occurs in the try block, throw keyword transfers the control of execution
to the caller by throwing an object of exception.
Only one object of exception type can be thrown by using throw keyword at a time. Throw
keyword can be used inside a method or static block provided that exception handling is
present.

Key points of Throw keyword:


1. In Java exception handling, we use throw keyword to throw a single exception explicitly.
It is followed by an instance variable.
2. Using throw keyword, we can throw either checked or unchecked exception in Java.
3. The keyword throw raises an exception by creating a subclass object of Exception
explicitly.
4. We mainly use throw keyword to throw custom exception on the basis of some specified
condition.
5. We use keyword throw inside the body of method or constructor to invoke an exception.
6. With the help of throw keyword, we cannot throw more than one exception at a time.

The syntax to throw an exception manually in Java is as follows:


throw exception_name;
Here, exception_name is a reference to an object of Throwable class or its subclass.
For example:
1. throw new ArithmeticException();
Or,
ArithmeticException ae = new ArithmeticException();
throw ae;
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

2. throw new NumberFormatException();

Control flow of try-catch block with Java throw Statement

When a throw statement is encountered in a program, the flow of execution of subsequent


statements stops immediately in the try block and the corresponding catch block is searched.
The nearest try block is inspected to see if it has a catch block that matches the type of
exception. If corresponding catch block is found, it is executed otherwise the control is
transferred to the next statement.
In case, no matching catch block is found, JVM transfers the control of execution to the
default exception handler that stops the normal flow of program and displays error message
on the output screen.
Java Throw Exception Example Program

Program code 1:
public class ThrowTest1 {
public static void main(String[] args) {

// Declaring a try-catch block.


try
{
// Creating an object of ArithmeticException class.

ArithmeticException a = new ArithmeticException("Hello from throw"); // Line 7


throw a; // Exception thrown explicitly. // Line 8

// Line 7 and 8 can be written also in one line like this:


// throw new ArithmeticException("Hello from throw");
}
catch(ArithmeticException ae)

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

{
System.out.println("ArithmeticException caught: \n" +ae);
System.out.println(ae.getMessage());
}
}
}

Program code 2:
public class ThrowTest2 {
public static void main(String[] args)
{
int x = 20;
int y = 0;
try
{
int z = x/y; // Exception occurred. // Line 9
System.out.println("Result: " +z); // Line 10
throw new ArithmeticException();
}
catch(ArithmeticException ae) {
System.out.println("Exception caught: \n" +ae);
}
}
}

Program code 3:
public class ThrowTest3 {
public static void main(String[] args)
{

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

int x = 20;
int y = 0;

try
{
int z = x/y;
throw new ArithmeticException();
System.out.println("Result: " +z); // Unreachable code.
}
catch(ArithmeticException ae) {
System.out.println("Exception caught: \n" +ae);
}
}
}
User defined Exception in Java with Example
Sometimes, predefined exceptions in Java are not suitable for describing a certain
situation. In other words, the predefined exception classes of Java do not fit as per our
needs in certain scenarios.
In such cases, the programmer wants to create his own customized exception as per
requirements of the application, which is called user-defined exception or custom
exception in Java.
User-defined exceptions in Java are those exceptions that are created by a programmer (or
user) to meet the specific requirements of the application. That’s why it is also known as
user-defined exception. It is useful when we want to properly handle the cases that are
highly specific and unique to different applications. For example:
1. A banking application, a customer whose age is lower than 18 years, the program throws
a custom exception indicating “needs to open a joint account”.
2. Voting age in India: If a person’s age entered is less than 18 years, the program throws
“invalid age” as a custom exception.
Actually, there are mainly two drawbacks of predefined exception handling mechanism.
They are:
• Predefined exceptions of Java always generate the exception report in a predefined
format.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

• After generating the exception report, it immediately terminates the execution of


the program.
The user-defined exception handling mechanism does not contain the above explained two
drawbacks. It can generate the report of error message in any special format that we prefer.
It will automatically resume the execution of the program after generating the error report.

How to Create Your Own User-defined Exception in Java?

There are the following steps that are followed in creating a user-defined exception or
custom exception in Java. They are as follows:
Step 1: User-defined exceptions can be created simply by extending the Exception class.
This is done as:
class OwnException extends Exception
Here, we have defined our own exception class named OwnException as a subclass of an
existing Java Exception class. Throwable class is the superclass for an entire family of
exception classes, which is declared in java.lang.Throwable package.
Step 2: If you do not want to store any exception details, define a default constructor in
your own exception class. We can do this as follows:
OwnException()
{

}
Step 3: If you want to store exception details, define a parameterized constructor with
string as a parameter, call the superclass (Exception) constructor from this, and store
variable “str”. This can be done as follows:
OwnException(String str)
{
super(str); // Call superclass exception constructor and store variable "str" in it.
}
Step 4: In the last step, we need to create an object of the user-defined exception class and
throw it using throw clause.

OwnException obj = new OwnException("Exception details");

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

throw obj;
or,
throw new OwnException("Exception details");
Program code 1:
package customExceptionProgram;
// Define a custom exception class that extends Exception
public class OwnException extends Exception
{
// Declare default constructor.
OwnException()
{

}
}
public class MyClass {
public static void main(String[] args)
{
try
{
// Create an object of user defined exception and throw it using throw clause.
OwnException obj = new OwnException();
throw obj;
}
catch (OwnException ex)
{
System.out.println("Caught a user defined exception");
}
}
}

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Program code 2:
package customExceptionProgram;
// Define a user-defined exception class that extends Exception
public class OwnException extends Exception
{
// Declare a parameterized constructor with a parameter str of type string.
OwnException(String str)
{
super(str); // Call super exception class constructor.
}
}
public class MyClass {
public static void main(String[] args)
{
try
{
// Create an object of user defined exception and throw it using the throw clause.
OwnException obj = new OwnException("Creating user defined exception");
throw obj;

// or, throw new OwnException("Creating user defined exception");


}
catch (OwnException ex)
{
System.out.println("Caught a user defined exception");
System.out.println(ex.getMessage());
}
}

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Program code 5:
package customExceptionProgram;
// Define a custom exception class that extends Exception
class MyException extends Exception {

// Create a constructor for the exception class


public MyException(String str) {
super(str);
}
}
import java.util.Scanner;
public class SquareCalculator {
public static void main(String[] args)
{
// Create an object of Scanner class to read the input.
Scanner sc = new Scanner(System.in);

try {
System.out.print("Enter a number less than 100: ");
int number = sc.nextInt();
int square = number * number;
if (number >= 100)
{
// If the number is greater than 100, throw the custom exception
throw new MyException("Please enter a number less than 100");
} else {
System.out.println("Square of " + number + " is " + square);

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

}
} catch (MyException e) {
// Catch and handle the custom exception
System.out.println("Custom Exception Caught: " + e.getMessage());
} catch (Exception e) {
// Handle other exceptions, e.g., if the user enters non-numeric input
System.out.println("An error occurred: " + e.getMessage());
} finally {
sc.close();
}
}
}

Throws Keyword in Java | Throws Clause


In Java, sometimes a method may throw an exception in a program but cannot handle it
due to not have an appropriate exception handling mechanism.
In such a case, the programmer has to throw that exception to the caller of the method
using throws clause.
Throws clause consists of throws keyword followed by a comma-separated by the list of
all exceptions thrown by that method.
Throws Keyword in Java

Throws keyword in Java is used in the method declaration. It provides information to the
caller method about exceptions being thrown and the caller method has to take the
responsibility of handling the exception.
Throws keyword is used in case of checked exception only because if we are not handling
runtime exceptions (unchecked exceptions), Java compiler does not give any error related
to runtime exceptions. If an error occurs, we are unable to do anything.
When the code generates a checked exception inside a method but the method does not
handle it, Java compiler detects it and informs us about it to handle that exception.
In this case, compulsorily, we must handle that checked exception otherwise we will get an
error flagged by Java compiler.

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

To prevent this error flagged by the compiler, we need to handle exceptions using throw
clause. There are two ways to handle the exception:
• By using try-catch block
• By using throws keyword
Key Points of Throws Keyword
1. In Java exception handling, we use throws keyword to define a list of exceptions which
may be thrown by that method.
2. We can use throws keyword in method or constructor declaration (signature) to denote
exceptions that can be possibly thrown by that method.
3. Throws is followed by the exception class name.
4. With throws clause, we can declare more than one exception.
Syntax to declare Throws Keyword

The general syntax of using throws statement with a method declaration is as follows:
Syntax:
access_specifier return_type method_name(parameter list) throws exception
{
// body of the method.
}
Java throws keyword can be used to throw multiple exceptions thrown by a method at a
time. Multiple exceptions thrown by a method can be declared by separating them in a
comma with the help of throws keyword.
The general syntax to throw multiple exceptions thrown by a method is as follows:
Syntax:
access_specifier return_type method_name(parameter_list) throws exception1, exception2,
. . . . exceptionN
{
// body of the method.
}
Throws Exception Example Programs

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Let’s take a simple example program to understand throws clause better, where there is an
InterruptedException raised by sleep() method.
Program code 1:
public class ThrowsTest1 {
public static void main(String[] args)
{
Thread.sleep(1000);
System.out.println("Hello Java");
}
}

CHAINED EXCEPTIONS
Chained Exceptions allows to relate one exception with another exception, i.e one ex-
ception 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
actualcause 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 theactual cause of exception. Chained Exception is used in such type of situations.
Throwable constructors that supports chained exceptions are:
1. Throwable(Throwable cause) :- Where cause is the exception that causes the
current
exception.
2. Throwable(String msg, Throwable cause) :- Where msg is the exception message
and
cause is the exception that causes the current exception.
Throwable methods that supports chained exceptions are:
1. getCause() method :- This method returns actual cause of an exception.
2. initCause(Throwable cause) method :- This method sets the cause for the calling
ex-ception.

Example:
import java.io.IOException;
public class ChainedException
{
public static void divide(int a, int b)
{
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

if(b==0)
{
ArithmeticException ae = new ArithmeticException(“top layer”);
ae.initCause( new IOException(“cause”) );
throw ae;
}
else
{
System.out.println(a/b);
}
}
public static void main(String[] args)
{
try {
divide(5, 0);
}
catch(ArithmeticException ae)

System.out.println( “caught : “ +ae);


System.out.println(“actual cause: “+ae.getCause());
}
}
}
Sample Output:
caught : java.lang.ArithmeticException: top
layeractual cause: java.io.IOException: cause

In this example, the top-level exception is ArithmeticException. To it is added a cause


exception, IOException. When the exception is thrown out of divide( ), it is caught by main(
).There, the top-level exception is displayed, followed by the underlying exception, which
isobtained by calling getCause( ).

STACK TRACE ELEMENT


The StackTraceElement class element represents a single stack frame which is a stack trace
when an exception occurs. Extracting stack trace from an exception could provide use-ful
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

information such as class name, method name, file name, and the source-code line num-
ber. The getStackTrace( ) method of the Throwable class returns an array of StackTraceEle-
ments.
StackTraceElement class constructor
StackTraceElement(String declaringClass, String methodName, String fileName, int
lineNumber)
This creates a stack trace element representing the specified execution point.

Stack Trace Element class methods

Method Description
boolean equals(Object obj) Returns true if the invoking StackTraceElement is the
same as the one passed in obj. Otherwise, it returns false.
String getClassName() Returns the class name of the execution point
String getFileName( ) Returns the filename of the execution point
int getLineNumber( ) Returns the source-code line number of the execution
point
String getMethodName( ) Returns the method name of the execution point
String toString( ) Returns the String equivalent of the invoking sequence
Example:
public class StackTraceEx{
public static void main(String[] args) {
try{
throw new RuntimeException(“go”); //raising an runtime exception
}
catch(Exception e){
System.out.println(“Printing stack trace:”);
//create array of stack trace elements
final StackTraceElement[] stackTrace = e.getStackTrace();
for (StackTraceElement s : stackTrace) {
System.out.println(“\tat “ + s.getClassName() + “.” + s.getMethodName()
+ “(“ + s.getFileName() + “:” + s.getLineNumber() + “)”);
}
}
}
}

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering

Sample Output:
Printing stack trace:
at StackTraceEx.main(StackTraceEx.java:5)

SUDHAKAR DWIVEDI-IMSEC-GZB-CSE

You might also like