You are on page 1of 34

Java Exception Handling

Java Exception Handling


 Exception Handling is a mechanism to handle exception at
runtime. Exception is a condition that occurs during program
execution and lead to program termination abnormally. There can
be several reasons that can lead to exceptions, including
programmer error, hardware failures, files that need to be opened
cannot be found, resource exhaustion etc.
 Java Exception
 A Java Exception is an object that describes the exception that occurs in a
program. When an exceptional events occurs in java, an exception is said
to be thrown. The code that's responsible for doing something about the
exception is called an exception handler

Ms Anosha Khan 02/24/2024 2


How to Handle Exception

 Java provides controls to handle exception in the program. These


controls are listed below.
 Try : It is used to enclose the suspected code.
 Catch: It acts as exception handler.
 Finally: It is used to execute necessary code.
 Throw: It throws the exception explicitly.
 Throws: It informs for the possible exception.

Ms Anosha Khan 02/24/2024 3


Types of Exceptions

 In Java, exceptions broadly can be categories into checked exception, unchecked


exception and error based on the nature of exception.
 Checked Exception
 The exception that can be predicted by the JVM at the compile time for example : File that
need to be opened is not found, SQLException etc. These type of exceptions must be checked
at compile time.
 Unchecked Exception
 Unchecked exceptions are the class that extends RuntimeException class. Unchecked exception
are ignored at compile time and checked at runtime. For example : ArithmeticException,
NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked
at runtime.
 Error
 Errors are typically ignored in code because you can rarely do anything about an error.
For example, if stack overflow occurs, an error will arise. This type of error cannot be handled
in the code
Ms Anosha Khan 02/24/2024 4
Hierarchy of Java Exception
classes

Ms Anosha Khan 02/24/2024 5


Common Scenarios of Java Exceptions

 A scenario where ArithmeticException occurs


 If we divide any number by zero, there occurs an ArithmeticException.
 int a=50/0;//ArithmeticException
 A scenario where NullPointerException occurs
 If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
 String s=null;
 System.out.println(s.length());//NullPointerException
 A scenario where NumberFormatException occurs
 If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a
string variable that has characters; converting this variable into digit will cause NumberFormatException.
 String s="abc";
 int i=Integer.parseInt(s);//NumberFormatException
 A scenario where ArrayIndexOutOfBoundsException occurs
 When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the following statements.
 int a[]=new int[5];
 a[10]=50; //ArrayIndexOutOfBoundsException
Ms Anosha Khan 02/24/2024 6
How to Use the Try-catch Clause?
try {
// block of code to monitor for errors
// the code you think can raise an exception
} catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
} catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally { // block of code to be executed after try block ends
}

Ms Anosha Khan 02/24/2024 7


Ms Anosha Khan 02/24/2024 8
Methods to print the Exception information:

class Main{
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

Ms Anosha Khan 02/24/2024 9


Methods to print the Exception information:

 printStackTrace()
 This method prints exception information in the format of the Name of the
exception: description of the exception, stack trace.
 toString()
 The toString() method prints exception information in the format of the
Name of the exception: description of the exception.
 getMessage()
 The getMessage() method prints only the description of the exception.

Ms Anosha Khan 02/24/2024 10


How Does JVM Handle an Exception?

 Default Exception Handling: Whenever inside a method, if an exception


has occurred, the method creates an Object known as an Exception Object
and hands it off to the run-time system(JVM). The exception object
contains the name and description of the exception and the current state
of the program where the exception has occurred. Creating the Exception
Object and handling it in the run-time system is called throwing an
Exception. There might be a list of the methods that had been called to get
to the method where an exception occurred. This ordered list of methods is
called Call Stack.
 following procedure will happen.
 The run-time system searches the call stack to find the method that contains a
block of code that can handle the occurred exception. The block of the code is
called an Exception handler.
 The run-time system starts searching from the method in which the exception
occurred and proceeds through the call stack in the reverse order in which
methods were called.
Ms Anosha Khan 02/24/2024 11
How Does JVM Handle an Exception?(Cont.)
 If it finds an appropriate handler, then it passes
the occurred exception to it. An appropriate
handler means the type of exception object
thrown matches the type of exception object it
can handle.
 If the run-time system searches all the methods
on the call stack and couldn’t have found the
appropriate handler, then the run-time system
handover the Exception Object to the default
exception handler, which is part of the run-
time system. This handler prints the exception
information in the following format and
terminates the program abnormally.
Exception in thread "xxx" Name of Exception :
Description
... ...... .. // Call Stack

Ms Anosha Khan 02/24/2024 12


Examples for Multiple Catch blocks

class Main{
public static void main(String[] args) {
try
{
Integer in = new Integer(“abc");
in=12/0;
System.out.println(in);
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic " + e);
}
catch (NumberFormatException e)
{
System.out.println("Number Format Exception " + e);
}
}
}
Ms Anosha Khan 02/24/2024 13
Example for Unreachable Catch block
public class Main
{
public static void main(String[] args)
{
try While using multiple catch block, always make sure that sub-
{
int a[]=new int[10];
classes of Exception class comes before any of their super
System.out.println(a[20]); classes. Else you will get compile time error.
}
catch(Exception e)
{
System.out.println("Arithmetic Exception --> "+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception --> "+e);
}
catch(Exception e)
{
System.out.println(e);
Ms Anosha Khan
} 02/24/2024 14
}
}
Nested try statement
class Main
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x = arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}

Ms Anosha Khan 02/24/2024 15


Java throw
 The throw keyword in Java is used to explicitly throw an exception from a
method or any block of code. We can throw either checked or unchecked
exception. The throw keyword is mainly used to throw custom exceptions.
 Syntax in Java throw
 throw Instance
 Example:
 throw new ArithmeticException("/ by zero");
 But this exception i.e., Instance must be of type Throwable or a subclass of
Throwable.
 The flow of execution of the program stops immediately after the throw
statement is executed and the nearest enclosing try block is checked to
see if it has a catch statement that matches the type of exception. If it
finds a match, controlled is transferred to that statement otherwise
next enclosing try block is checked, and so on. If no matching catch is
found then the default exception handler will halt the program.
Ms Anosha Khan 02/24/2024 16
Example
package main;
// Java program that demonstrates the use of throw
class Main {
static void fun(){
try {
throw new NullPointerException("demo");
}
catch (NullPointerException e) {
System.out.println("Caught inside fun()."+e);
throw e; // rethrowing the exception
}
}
public static void main(String args[]){
try {
fun();
}
catch (NullPointerException e) {
System.out.println("Caught in main."+e);
Ms Anosha Khan
} 02/24/2024 17
}
}
Example
package main;
// Java program that demonstrates the use of throw
class Main{
static void fun2(){
throw new NullPointerException("demo");
}
static void fun(){
fun2();
}
public static void main(String args[]){
try {
fun();
}
catch (NullPointerException e) {
System.out.println("Caught in main."+e);
}
}
}
Ms Anosha Khan 02/24/2024 18
Java throws

 throws is a keyword in Java that is used in the signature of a method to indicate that this
method might throw one of the listed type exceptions. The caller to these methods has to
handle the exception using a try-catch block.
 Syntax of Java throws
 type method_name(parameters) throws exception_list
 exception_list is a comma separated list of all the exceptions which a method might throw.
 In a program, if there is a chance of raising an exception then the compiler always warns us
about it and compulsorily we should handle that checked exception, Otherwise, we will get
compile time error saying unreported exception XXX must be caught or declared to be
thrown. To prevent this compile time error we can handle the exception in two ways:
 By using try catch
 By using the throws keyword
 We can use the throws keyword to delegate the responsibility of exception handling to the
caller (It may be a method or JVM) then the caller method is responsible to handle that
exception.

Ms Anosha Khan 02/24/2024 19


Example
// Java program to illustrate error in case class Main{
// of unhandled exception public static void main(String[] args)
throws InterruptedException
class Main{ {
public static void main(String[] args) Thread.sleep(10000);
System.out.println("Hello");
{ }
}
Thread.sleep(10000);//error
In the above program, by using the throws keyword we
System.out.println("Hello "); handled the InterruptedException and we will get the
output as Hello Geeks
}
}
In the above program, we are getting compile time error because there is a
chance of exception if the main thread is going to sleep, other threads get the
chance to execute the main() method which will cause InterruptedException.
Ms Anosha Khan 02/24/2024 20
Example
Important Points to Remember about
class Main{
throws Keyword
static void fun() throws IllegalAccessException
•throws keyword is required only for
{
checked exceptions and usage of the throws
System.out.println("Inside fun(). ");
keyword for unchecked exceptions is
throw new IllegalAccessException("demo");
meaningless.
}
•throws keyword is required only to
public static void main(String args[])
convince the compiler and usage of the
{
throws keyword does not prevent abnormal
try {
termination of the program.
fun();
•With the help of the throws keyword, we
}
can provide information to the caller of the
catch (IllegalAccessException e) {
method about the exception.
System.out.println("caught in main."+e);
}
}
}

Ms Anosha Khan 02/24/2024 21


Throwing multiple exceptions
class Main {
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {
// code that may produce NullPointerException
………
// code that may produce IOException
………
// code that may produce InvalidClassException
………
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e1){
System.out.println(e1.getMessage());
} catch(InvalidClassException e2){
System.out.println(e2.getMessage());
Ms Anosha Khan } 02/24/2024 22

}
Types of Builtin Exceptions in Java
 ArithmeticException: It is thrown when an exceptional condition has
occurred in an arithmetic operation.
 ArrayIndexOutOfBoundsException: It is thrown to indicate that an array
has been accessed with 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 class whose 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 doing some processing, and it is interrupted.
Ms Anosha Khan 02/24/2024 23
 NoSuchFieldException: It is thrown when a class does not contain the field (or variable)
specified
 NoSuchMethodException: It is thrown when accessing a method that is not found.
 NullPointerException: This exception is raised when referring to the members of a null
object. Null represents nothing
 NumberFormatException: This exception is raised when a method could not convert a
string into a numeric format.
 RuntimeException: This represents an exception that occurs during runtime.
 StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an
index is either negative or greater than the size of the string
 IllegalArgumentException : This exception will throw the error or error statement when
the method receives an argument which is not accurately fit to the given relation or
condition. It comes under the unchecked exception.
 IllegalStateException : This exception will throw an error or error message when the
method is not accessed for the particular operation in the application. It comes under the
unchecked exception.
 For example
 https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/
Ms Anosha Khan 02/24/2024 24
User-defined Custom Exception in Java
 Java provides us the facility to create our own exceptions which are basically
derived classes of Exception. Creating our own Exception is known as a custom
exception or user-defined exception. Basically, Java custom exceptions are used
to customize the exception according to user needs. In simple words, we can say
that a User-Defined Exception or custom exception is creating your own
exception class and throwing that exception using the ‘throw’ keyword.
 Why use custom exceptions?
 Java exceptions cover almost all the general types of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
 Following are a few of the reasons to use custom exceptions:
 To catch and provide specific treatment to a subset of existing Java exceptions.
 Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the
exact problem

Ms Anosha Khan 02/24/2024 25


Example
class MyException extends Exception {
MyException(String s){
// Call constructor of parent Exception In the above code, the constructor of
super(s); MyException requires a string as its
System.out.println("My customized method"); argument. The string is passed to the parent
} class Exception’s constructor using super().
} The constructor of the Exception class can
public class Main{ also be called without a parameter and the
// Driver Program call to super is not mandatory.
public static void main(String args[]){
try {
// Throw an object of user defined exception
throw new MyException("My Custom Exception");
}
catch (MyException ex) {
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage());
}
Ms Anosha Khan
} 02/24/2024 26

}
Another way class MyException extends Exception {
String msg;
MyException(String msg){
this.msg=msg;
System.out.println("my fun");
}
public String getMessage(){
return msg;
}}
public class Main {
public static void main(String args[]){
try {
throw new MyException("my msg");
}
catch (MyException ex) {
System.out.println("Caught");

Ms Anosha Khan
System.out.println(ex.getMessage());
02/24/2024 27

} } }
Java try with Resource Statement
 try with resource is a new feature of Java that was introduced in Java 7 and further improved in Java
9. This feature add another way to exception handling with resources management. It is also referred
as automatic resource management. It close resources automatically by using AutoCloseable
interface..
 Resource can be any like: file, connection etc and we don't need to explicitly close these, JVM will do
this automatically.
 Suppose, we run a JDBC program to connect to the database then we have to create a connection and
close it at the end of task as well. But in case of try-with-resource we don’t need to close the
connection, JVM will do this automatically by using AutoCloseable interface.
 Try with Resource Syntax
try(resource-specification(there can be more than one resource))
This try statement contains a parenthesis in which one or
{ more resources is declared. Any object that implements
//use the resource java.lang.AutoCloseable or java.io.Closeable, can be
passed as a parameter to try statement. A resource is an
}
object that is used in program and must be closed after
catch() the program is finished. The try-with-resources
{ statement ensures that each resource is closed at the
// handler code end of the statement of the try block. We do not have to
Ms Anosha Khan
explicitly close the resources. 02/24/2024 28
}
Example without using try with Resource Statement

class Main{
public static void main(String[] args){
try {
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br = new BufferedReader(new FileReader("d:\\
myfile.txt"));
while((str=br.readLine())!=null){
System.out.println(str);
}
br.close(); //closing BufferedReader stream
}
catch(IOException ie){
System.out.println("I/O Exception "+ie);

Ms Anosha Khan } 02/24/2024 29

}
Example try with Resource Statement
import java.io.*;
class Car{
public static void main(String[] args){
try(BufferedReader br = new BufferedReader(new
FileReader("myfile.txt"))){
String str;
while((str = br.readLine()) != null){
System.out.println(str);
}
}
catch(IOException ie){
System.out.println("I/O Exception "+ie);
}
}
Ms Anosha Khan 02/24/2024 30

}
Points to Remember

 A resource is an object in a program that must be closed after the program


has finished.
 Any object that implements java.lang.AutoCloseable or java.io.Closeable can
be passed as a parameter to try statement.
 All the resources declared in the try-with-resources statement will be closed
automatically when the try block exits. There is no need to close it explicitly.
 We can write more than one resources in the try statement.
 In a try-with-resources statement, any catch or finally block is run after the
resources declared have been closed.

Ms Anosha Khan 02/24/2024 31


Logging in Java

 Java provides the ability to capture the log files.


 The need for Log capture
There are multiple reasons why we may need to capture the application activity.
 Recording unusual circumstances or errors that may be happening in the program
 Getting the info about whats going in the application
 The details which can be obtained from the logs can vary. Sometimes, we may want a lot
of details regarding the issue, or sometimes some light information only.
Like when the application is under development and is undergoing testing phase, we may
need to capture a lot of details.
 Log Levels
The log levels control the logging details. They determine the extent to which depth the
log files are generated. Each level is associated with a numeric value and there are 7
basic log levels and 2 special ones.
We need to specify the desired level of logging every time, we seek to interact with the
log system.

Ms Anosha Khan 02/24/2024 32


The basic logging levels are

Level Value Used for

SEVERE 1000 Indicates some serious failure


Furthermore, there are two special Logging levels
WARNIN
900 Potential Problem
G
OFF Integer.MAX_VALUE Capturing nothing
ALL Integer.MIN_VALUE Capturing Everything
INFO 800 General Info Capturing everything may mean every field declaration,
definition, every method call, every assignment
CONFIG 700 Configuration Info performed etc.

FINE 500 General developer info

FINER 400 Detailed developer info

FINEST 300 Specialized Developer Info


Ms Anosha Khan 02/24/2024 33
basic logging levels
 Severe occurs when something terrible has occurred and the application cannot
continue further. Ex like database unavailable, out of memory.
 Warning may occur whenever the user has given wrong input or credentials.
 Info is for the use of administrators or advanced users. It denotes mostly the
actions that have lead to a change in state for the application.
 Configuration Information may be like what CPU the application is running on,
how much is the disk and memory space.
Fine Finer and Finest provide tracing information. When what is happening/ has
happened in our application.
 FINE displays the most important messages out of these.
 FINER outputs a detailed tracing message and may include logging calls
regarding method entering, exiting, throwing exceptions.
 FINEST provides highly detailed tracing message.

Ms Anosha Khan 02/24/2024 34

You might also like