L7 Exception Handling

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Exception Handling

Lecture Objectives

• To understand what is Error

• To understand Exception

• To understand Exceptions Handling

• try/catch block

• To understand use of throw keyword

• To understand the difference between checked and unchecked exceptions


Errors in Programs

Errors

Appear at execution time


Appear at compile time • Code is correct in terms of
syntax
• Code is not written
• Not detected by translator
according to the syntax
• Program can be executed
• Detected by translator
in presence of these errors
• Program cannot execute
but it will give wrong
until you correct them
output or terminate during
and compile successfully
execution
• Called Syntax Errors

Called Logical Called Run-time


Errors if they give Errors if program
wrong output get terminated
during execution
Note: Errors are the human mistakes that occurs while writing code in a programming language.
Examples of different types of Errors

Errors

Examples of Syntax Examples of Run-time


Errors Errors
sum=n1+n2+n3 Result=x/y;
Forget ; at the end of statement if the value of y is 0 (zero) then
answer will be infinity and
program will be terminated
System.out.print(“Hello);
Forget to close string with ”

Examples of Logical
Errors
Avg=5+7+9/3;
The value of Avg will be 15 which is
wrong average. The right average
value is 7.
Exceptions

• An exception is an event, which occurs during the


execution of a program, that disrupts the normal
flow of the program’s instructions.

• An exception is a problem that arises during the


execution of a program and that terminates the
execution of that program.
Hierarchy of Exception Classes

Exceptions is the
main class we use
for Exception
Handling
Exception Types
Exception Handling
Exceptional Handling is the process of
responding/handling to the occurrence of
Exceptions during the execution of
program so the remaining code can be
executed without terminating the program.
• Instead of programming for success
x.doSomething()

• You would always be programming for failure:

if (!x.doSomething()) return false;


Exception Handling Mechanism

There are 2 steps of Exception Handling Mechanism

1. Hit the Exception and Throw it – find where an exception can occur, create an
object of exception and throw it

2. Catch the Exception and Handle it – Catch the object of exception and perform
an appropriate action to handle the exception

Step 1 is implemented in Java with try block and step 2 is


implemented by catch block.
Exception Handling Mechanism
Syntax in Java
try Block try
contains the Exception
{
statement(s) that object
statement;
can cause an creator
}
Throws Exception
Exception
object catch Block catch(ExceptionClass obj)
contains the Exception {
statement(s) that handler statement;
handles the }
Exception

Statements in try block are executed: catch (ExceptionClass obj) block


- If no exceptions occur, catch blocks - obj contains reference to the exception
are skipped object that was thrown
- If exception of matching type occurs, - catch block takes appropriate action to
execution jumps to catch block handle the exception
Exception Handling Mechanism

Hierarchy of Exception Classes

catch(Exception e) This catch block will catch any type of Exception


{ because Exception is a super class of all types of
… exceptions.
} But if you want to catch/handle a particular type
of Exception then that type must be mentioned.
For Example:

catch(Arithmetic Exception e)
{

}
Example

public class Test {


public static void main(String args[]){
int a=20, b=10, c=10;
int x=a/(b-c);
System.out.println(“x = ”+x);
int y=a/(b+c);
System.out.println(“y = ”+y);
}
}

Is there any mistake in this code according to java syntax?


Example
public class Test {
public static void main(String args[]){
int a=20, b=10, c=10;
int x=a/(b-c);
System.out.println(“x = ”+x);
int y=a/(b+c);
System.out.println(“y = ”+y);
}
}

No, it is syntactically all right.

But x=a/(b-c) ….. will cause divide by zero exception


at run time. An object of Arithematic Exception will
be created and throw but no catch block is there.
Example

public class Test {


public static void main(String args[]){
int a=20, b=10, c=10;
This statement is causing
int x=a/(b-c); an exception so it must be
System.out.println(“x = ”+x); handled with try/catch
blocks.
int y=a/(b+c);
System.out.println(“y = ”+y);
}
}
Example
public class Test {
public static void main(String args[]){
int a=20, b=10, c=10;
try {
int x=a/(b-c);
System.out.println(“x = ”+x);
}
catch(ArithmeticException e) {
System.out.println(“Division by Zero”);
}
int y=a/(b+c);
Output
System.out.println(“y = ”+y);
} Division by Zero
} Y=1
Multiple catch blocks

A try block can have more than one catch blocks


try {
statement
statement
. . .
}
catch (ExceptionClass exceptionObject) {
statement
statement
. . .
}
catch (ExceptionClass exceptionObject) {
statement
statement
. . .
}
. . .
Example of multiple catch Blocks
Example:

try {
String filename = . . .;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
String input = in.next();
int value = Integer.parseInt(input);
. . .
}
catch (IOException exception) {
exception.printStackTrace();
}
catch (NumberFormatException exception) {
System.out.println("Input was not a number");
}
Use of throw keyword

• The throw keyword is used to explicitly/forcibly throw an exception from a


method or any block of code.

• The throw keyword is mainly used to throw custom exceptions


Use of try/catch block for “Division by zero”

public class Test {


public static void main(String args[]) {
int i=10, j=0, k;
try {
k=i/j;
System.out.println(“k = “+k);
}
catch(ArithmeticException e)
{
System.out.println(“Arithmetic Exception”);
}
System.out.println(“Hello…”);
}
}
How to create a customized Exception

public class Test {


public static void main(String args[]) {
int i=10, j=0, k;
try {
/ is replaced by * that will cause
no exception but a customized
k=i*j; exception is required

System.out.println(“k = “+k);
}
catch(ArithmeticException e) {
System.out.println(“Arithmetic Exception”);
}
System.out.println(“Hello…”);
}
}
Use of throw keyword for a customized Exception

public class Test {


public static void main(String args[]) {
int i=10, j=0, k;
a customized exception is
try { created using throw keyword
k=i*j;
if(k==0) { throw new ArithmeticException(); }
System.out.println(“k = “+k);
}
catch(ArithmeticException e) {
System.out.println(“Arithmetic Exception”);
}
System.out.println(“Hello…”);
}
}
Syntax: throw an Exception

throw exceptionObject;

Example:
throw new ArithmeticException();

Purpose:
To throw an exception and transfer control to a handler for this
exception type
Checked and Unchecked Exceptions

• Two types of exceptions:


• Checked:
• Checked Exceptions are the exceptions which requires to be handled at compile time.
• All classes that inherit from class Exceptions (but not directly/indirectly from class
RuntimeException).
• These exceptions are typically caused by conditions which are not under control of
program code.
• For example, FileNotFoundException

• Unchecked:
• Unchecked Exceptions are the exceptions which are not required to be handled at
compile time.
• All classes that direct/indirect subclasses of RuntimeException are unchecked
exceptions.
• These exceptions are caused by defects in programs code so they are programmer’s
faults.
• For example, IllegalArgumentException
Checked and Unchecked Exceptions (Cont’d)

• For example, use a Scanner to read a file


String filename = . . .;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);

• But, FileReader constructor can throw a


FileNotFoundException
Checked and Unchecked Exceptions (Cont’d)

• Two choices:
• Handle the exception
• Tell compiler that you want method to be terminated when the exception
occurs
• Use throws specifier so method can throw a checked exception

public void read(String filename) throws FileNotFoundException


{
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
. . .
}
Checked and Unchecked Exceptions (Cont’d)

• For multiple exceptions:

public void read(String filename)


throws IOException, ClassNotFoundException

• Keep in mind inheritance hierarchy:


If method can throw an IOException and FileNotFoundException, only use
IOException

• Better to declare exception than to handle it incompetently


Syntax: throws keyword

accessSpecifier returnType
methodName(parameterType parameterName, . . .)
throws ExceptionClass, ExceptionClass, . . .

Example:
public static void main(String args[]) throws IOException

Purpose:
To indicate the checked exceptions that this method can throw

You might also like