Lecture – 13
Exceptions Handling in Java
Mohammad Hasan
Assistant Professor & Adjunct Faculty
Department of CSE, NDUB
Contents
Java – Exceptions Handling
2
Exceptions Handling
Difference between Error and Exception
Errors:
Indicate serious problems and abnormal conditions that most applications should not try to handle.
Error defines problems that are not expected to be caught under normal circumstances by our program.
For example:
memory error, hardware error, JVM error etc.
Errors are typically ignored in code because you can rarely do anything about an error.
Example: if stack overflow occurs, an error will arise. This type of error is not possible handle in code.
Exceptions:
Exception is an abnormal condition.
An exception (or exceptional event) is a problem that arises during the execution of a program.
In java, exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
What is exception handling?
Exception Handling is a mechanism to handle runtime errors
such as:
ClassNotFound, IO, SQL, Remote etc.
Java – Exceptions
An exception can occur for many different reasons, below given are
some scenarios where exception occurs.
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the
JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer
error, and others by physical resources that have failed in some manner.
Advantage of Exception Handling
The core advantage of exception handling is to
maintain the normal flow of the application.
Let's take a scenario:
Suppose there is 10 statements in your program and
there occurs an exception at statement 5, rest of the
code will not be executed i.e. statement 6 to 10 will not
run. If we perform exception handling, rest of the
statement will be executed. That is why we use
exception handling in java.
Types of Exception
There are mainly two types of exceptions: checked and unchecked
where error is considered as unchecked exception.
The sun microsystem says there are three types of exceptions:
Checked Exception
Unchecked Exception
Error
1. Checked exceptions
All exceptions other than Runtime Exceptions are known as
Checked exceptions as the compiler checks them during
compilation
A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions.
These exceptions cannot simply be ignored at the time of compilation
Examples of Checked Exceptions :
Some checked exceptions are as follows:
ClassNotFoundException
IllegalAccessException
NotSuchFieldException
EOFExceptionException
2. Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the
compiler do not check whether the programmer has handled them
or not
These exceptions need not be included in any method’s throws list
because compiler does not check to see if a method handles or throws
these exceptions.
Examples of Unchecked
Exceptions :
Some unchecked exceptions are as follows:
ArithmaticException
ArrayIndexOutOfBoundException
NullPointerException
NegativeArraySizeException
Hierarchy of Java Exception classes
Exception classes
Difference between checked and unchecked
exceptions
Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions [Link], SQLException etc. Checked exceptions are checked at compile-time.
Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions
[Link],NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Common scenarios where exceptions may
occur
1. Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
2. Scenario where NullPointerException occurs
NullPointerException
Common scenarios where exceptions may
occur
3. Scenario where NumberFormatException occurs
4. Scenario where ArrayIndexOutOfBoundsException occurs
Example: ArrayIndexOutOfBoundsException
public class Unchecked_Demo {
public static void main(String args[]){
int num[]={1,2,3,4};
[Link](num[5]);
}
}
If you compile and execute the above program you will get exception as shown below.
Exception in thread "main" [Link]: 5
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
try
catch
finally
throw
throws
try catch in java
Syntax of try catch in java
Problem without exception handling
Let's try to understand the problem if we don't use try-catch block.
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0; //may throw exception
[Link]("rest of the code...");
}
}
Output:
Exception in thread main [Link]:/ by zero
Solution by exception handling
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}
catch (ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code...");
}
}
Output:
Exception in thread main [Link]:/ by zero
Flow of control in try/catch blocks:
* When exception doesn’t occur
int x = 10;
int y = 10;
try {
int num= x/y;
[Link]("next-statement: Inside try block");
}
catch (Exception ex)
{
[Link]("Exception");
}
[Link]("next-statement: Outside of try-catch");
• Output:
next-statement: Inside try block
next-statement: Outside of try-catch
• In the above example exception didn’t occur in try block so catch block didn’t run.
Flow of control in try/catch blocks:
* When exception occurs
int x = 10;
int y = 0;
try {
int num= x/y;
[Link]("next-statement: Inside try block");
}
catch (Exception ex)
{
[Link]("Exception Occured");
}
[Link]("next-statement: Outside of try-catch");
• Output:
Exception Occurred
next-statement: Outside of try-catch
• Point to note in above example: There are two statements present inside try block. Since exception occurred
because of first statement, the second statement didn’t execute. Hence we can conclude that if an exception
occurs then the rest of the try block doesn’t execute and control passes to catch block.
Multiple catch blocks
try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3) • Output:
{ Array Index Out Of Bounds Exception
//Catch block
}
The finally block
The finally block follows a try block or a catch block.
A finally block of code always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to
execute, no matter what happens in the protected code.
A finally block appears at the end of the
try blocks and has the following syntax:
try
{
//statements that may cause an exception
}
finally
{
//statements to be executed
}
A finally block appears at the end of the
catch blocks and has the following syntax:
try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
finally
{
//The finally block always executes.
}
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
Syntax of throw keyword:
throw new exception_class("error message");
throw keyword example
Java throws keyword
SELF STUDY
Questions?
What is the difference between checked and unchecked exceptions ?
What happens behind the code int data=50/0; ?
Why use multiple catch block ?
Is there any possibility when finally block is not executed ?
What is exception propagation ?
What is the difference between throw and throws keyword ?
What are the 4 rules for using exception handling with method
overriding ?
Thank You