Unit-2 Exception Handling
Unit-2 Exception Handling
UNIT – 2
EXCEPTION HANDLING
Types of Errors:
Errors may broadly be classified in to two categories.
❖ Compile time error
❖ Run time 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
{
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
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.
try
{
{
// 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(
)
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
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
{
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:
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
try
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
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)
{
}
....
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..”);
}
}
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.
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 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
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();
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.
System.out.println(num);
}
catch(NumberFormatException 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
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
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");
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
▪ 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
Program code 1:
public class ThrowTest1 {
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
{
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
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.
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;
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 {
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 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)
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.
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