0% found this document useful (0 votes)
37 views

Chapter 6 Exception Handling

Uploaded by

ktesfaneh2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Chapter 6 Exception Handling

Uploaded by

ktesfaneh2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Object Oriented Programming

Chapter - 6
Exception Handling

Compiled By Yohans Samuel(MSc)

1
Contents

Exception Handling

1. Exception handling overview


2. The causes of exceptions
3. The Throwable class hierarchy
4. Handling of an exception
5. The throw statement
6. The finally clause
7. User defined exceptions

2
Exception (1)
• Exception is an abnormal condition. In Java, an exception is an
event that disrupts the normal flow of the program.
• It is an object which is thrown at runtime.
• Exception handling is the process of responding to the
occurrence of exceptions , anomalous or exceptional
conditions requiring special processing during the execution of
a program.
• In general, an exception breaks the normal flow of execution
and executes a pre-registered exception handler;
– the details of how this is done depend on whether it is a
hardware or software exception and how the software
exception is implemented.

3
Exception (2)
• Exception handling deals with these events to avoid the program or system
crashing, and without this process, exceptions would disrupt the normal
operation of a program.
• It is an event which occurs during the execution of a program, that disrupts
the normal program flow and may cause a program to fail.
• All of these problems have to be handled using exception handling.

4
Exception (3)
 An exception is a problem that arises during the execution of a program. It is a
representation of an error condition or a situation that is not the expected result of
a method/program.
 An exception can occur for various reasons:-
 Attempting to divide by zero (arithmetic exception)
 Reading a decimal value when an integer is expected (number format
exception)
 Attempting to write to a file that doesn't exist (I/O exception).
 Access an element past the end of an array.
(ArrayIndexOutOfBoundsException)
 or referring to a nonexistent character in a string (StringIndexOutOfBounds
exception).
 Invoke a method on a reference variable with null value.
(NullPionterException)
 A network connection has been lost in the middle of communications, or the
JVM has run out of memory.
5
Java’s Exception Hierarchy (1)
 The Java class library contains a number of predefined exceptions.
 All exception classes are subtypes of the java.lang.Exception class.
 The exception class is a subclass of the Throwable class. Other than the
exception class there is another subclass called Error which is derived from
the Throwable class.
 The Throwable class is contained in the java.lang package and subclass of
Throwable are contained in various packages.
– Example: Errors related to GUI components are included in the java.awt
 Errors are not normally trapped from the Java programs.
 These conditions normally happen in case of severe failures, which are not
handled by the java programs.
 Errors are generated to indicate errors generated by the runtime environment.
 Example : JVM is out of Memory. Normally programs cannot recover from
errors.

6
Java’s Exception Hierarchy (2)

7
Java’s Exception Hierarchy (3)
ClassNotFoundExceptio
n

IOException
ArithmeticExceptio
n
Exception AWTException
NullPointerExceptio
n
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineErro
r
Error
AWTError

Several more classes

8
Java’s Exception Hierarchy (4)
 To understand how exception handling works in Java, we need to
understand the three categories of exceptions:
Checked exceptions:-
 A checked exception is one that can be analyzed (can’t be
ignored) by the Java compiler.
 That is when the compiler encounters one of these exceptions it
checks whether the program either handles or declares the
exception.
 A checked exception is an exception that is typically a user error
or a problem that cannot be foreseen by the programmer.
 For example, if a file is to be opened, but the file cannot be
found, an exception occurs.

9
Java’s Exception Hierarchy (5)
Runtime exceptions:
 Runtime exception is an exception that occurs that probably could have
been avoided by the programmer.
 As opposed to checked exceptions, runtime exceptions are ignored at the
time of compilation.
 Runtime Exception is caused by programming errors, such as bad casting,
accessing an out-of-bounds array, and numeric errors
Errors:
 These are not exceptions at all, but problems that arise beyond the control
of the user or the programmer.
 Errors are typically ignored in your code because you 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.

10
Java’s Exception Hierarchy (6)
• Errors are thrown by JVM and represented in the Error class.
• The Error class describes internal system errors.
• Such errors rarely occur. If one does, there is little you can do
beyond notifying the user and trying to terminate the program
gracefully.
• RuntimeException, Error and their subclasses are known as
unchecked exceptions.
• All other exceptions are known as checked exceptions,
meaning that the compiler forces the programmer to check and
deal with the exceptions.

11
Exception Handling (1)
 Exception handling is the technique of catching the
exceptions that might be thrown some time in the future during
runtime.
 Exceptions can be handled in traditional way of handling errors
within a program with Java's default exception-handling
mechanism or using Exception class defined in Java API.
 Consider the following example

public double avgFirstN(int N) {


int sum = 0;
for(int k = 1; k <= N; k++)
sum += k;
return sum/N; // What if N is 0?
}
12
Exception Handling (2)
public double avgFirstN(int N) {
int sum = 0;
if (N <= 0) {
System.out.println("ERROR avgFirstN: N <= 0. Program terminating.");
System.exit(0); The error-handling code is built right into the
} algorithm
for (int k = 1; k <= N; k++)
sum += k;
return sum/N; // What if N is 0?
} // avgFirstN()

 This method has several problems


 programmer must remember to always check the return value
and take appropriate action.
 This requires much code (methods are harder to read) and
something may get overlooked.
13
Exception Handling (3)

14
Exception Handling (4)

15
Exception Handling (5)
How do you handle exceptions?
 Java exception handling is managed via five keywords: try,
catch, throw, throws, and finally.
 Java exception handling is a mechanism for handling exception
by detecting and responding to exceptions in a systematic,
uniform and reliable manner.
 Exception handling is accomplished through the “try – catch”
mechanism, or by a “throws or throw” clause in the method
declaration.
method1() { declare exception
method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}

16
Exception Handling (6)
v How do you handle exceptions? Use Five keywords for
Handling the Exception
• try
• catch
• finally
• throws
• throw

17
try - catch block (1)
Try-Catch Mechanism
 Wherever your code may trigger an exception, the normal code
logic is placed inside a block of code starting with the “try”
keyword.
 After the try block, the code to handle the exception should it
arise is placed in a block of code starting with the “catch”
keyword.
 You might like to think of these as "try to do this task" and if
there is an exception "catch the exception and do something
about it".
 A try/catch block is placed around the code that might generate
an exception.

18
try - catch block (2)
• Code within a try/catch block is referred to as protected code.
• You may also write an optional “finally” block. This block contains
code that is ALWAYS executed, either after the “try” block code, or
after the “catch” block code.
• Finally blocks can be used for operations that must happen no matter
what (i.e. cleanup operations such as closing a file)
• Generally, the try statement contains and guards a block of statements.
• Syntax of try catch
try {
codes that may throw exception(s)
}
catch (exception_type1 identifier){
//how do you want to deal with this exception
}
catch (exception_type2 identifier){
//how do you want to deal with this exception
}
// you can use multiple catches to handle different exceptions 19
try - catch block (3)
 A catch statement involves declaring the type of exception you
are trying to catch.
 If an exception occurs in protected code, the catch block (or
blocks) that follows the try is checked.
 If the type of exception that occurred is listed in a catch block,
the exception is passed to the catch block much as an argument
is passed into a method parameter.
 Only one catch block, that is the first applicable one, will be
executed.
 If no exceptions arise during the execution of the try block, the
catch blocks are skipped.

20
try - catch block (4)

import java.util.Scanner;

public class ExceptionDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
If an exception occurs on this line,
the rest of the lines in the method // Display the result
are skipped and the program is
System.out.println(
terminated.
"The number entered is " + number);
}
}
Terminated.
21
try - catch block (5)
import java.util.*;

public class HandleExceptionDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean continueInput = true;

do {
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
If an exception occurs on this line,
the rest of lines in the try block are
skipped and the control is // Display the result
transferred to the catch block. System.out.println(
"The number entered is " + number);

continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
scanner.nextLine(); // discard input
}
} while (continueInput);
} 22
}
try - catch block (6)
java import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :"+ a[3]);
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
} 23
try - catch block (7)

24
try - catch block (8)
 A catch block will catch exceptions of the class specified,
including any exceptions that are subclasses of the one
specified.
 The order in which exceptions are specified in catch blocks is
important.
 A compilation error will result is a catch block for a superclass
type appears before a catch block for a subclass type.
 A more specific catch block must precede a more general one
in the source.
 Failure to meet this ordering requirement causes a compiler
error.

25
try - catch block (9)
try { try {
..….. ..…..
} }
catch(Exception ex){ catch(RuntimeException ex){
……. ……
} }
catch (RuntimeException ex) { catch (Exception ex ) {
…….. ……..
} }

(a) Wrong order (b) Correct Order

26
finally Keyword (1)
 The finally keyword is used to create a block of code that
follows a try block.
 A finally block of code always executes, whether or not an
exception has occurred.
 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 catch blocks and has
the following syntax:

27
finally Keyword (2)
try{
codes that may throw exception(s)
}
catch (exception_type1 identifier){
//how do you want to deal with this exception
}
catch (exception_type2 identifier){
//how do you want to deal with this exception
}
// you can use multiple catches to handle different
exceptions
finally {
// code that must be executed under successful or
unsuccessful conditions
} 28
finally Keyword (3)
• The finally block is always executed regardless of an exception
occurrence or not, except for the following conditions:
• The death of the thread
• The use of System.exit( )
• Turning off the power to the CPU
• An exception arising in the finally block itself
• Note the followings:
 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses when ever a
try/catch block is present.
 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. 29
finally Keyword (4)
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{ System.out.println("Access element three :" + a[3]); }
catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception
thrown :" + e); }
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}}}
Output:
Exception thrown:java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

30
throws/throw Keyword (1)
The throws/throw Keywords:-
 In any method that might throw an exception, you may declare
the method as “throws” that exception, and thus avoid
handling the exception yourself.
 The throws keyword appears at the end of a method's signature.
public void myMethod() throws IOException
Example
public void myMethod throws IOException {
normal code with some I/O
}
 Every method must declare the types of checked exceptions
it might throw using throws keyword.

31
throws/throw Keyword (2)
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo"); }
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}}}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo

32
throws/throw Keyword (3)
• A method can declare that it throws more than one exception,
in which case the exceptions are declared in a list separated
by commas.
public void myMethod()throws Exception1, Exception2,….
ExceptionN
• Java forces you to deal with checked exceptions.
• If a method declares a checked exception (i.e., an exception
other than Error or RuntimeException), you must invoke it in
a try-catch block or declare to throw the exception in the calling
method.

33
throws/throw Keyword (4)
• Throw is a keyword in java language which is used to throw
any user defined exception to the same signature of method in
which the exception is raised.
• Throw keyword always should exist within method body.
• whenever method body contain throw keyword than the caller
method should be followed by throws keyword.

34
throws/throw Keyword (5)
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:not valid

35
throws/throw Keyword (6)

36
Try-with-resources (1)
• The Java try with resources construct, AKA Java try-with-
resources, is an exception handling mechanism that can
automatically close resources like
– a Java InputStream or
– a JDBC Connection when you are done with them.
• To do so, you must open and use the resource within a Java
try-with-resources block.
• When the execution leaves the try-with-resources block, any
resource opened within the try-with-resources block is
automatically closed,
– regardless of whether any exceptions are thrown either from inside
the try-with-resources block, or
– when attempting to close the resources.

37
Try-with-resources (2)
private static void printFile() throws IOException {

try(FileInputStream input = new FileInputStream("file.txt")) {

int data = input.read();


while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}

38
Try-with-resources (3)
• The simple and obvious way to use the new try-with-resources
functionality is to replace the traditional and verbose try-catch-finally block.
• The following code is a typical try-catch-finally block:
Scanner scanner = null;
try {
scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
39
Try-with-resources (4)
• and here’s the new super succinct solution using try-with-resources:
try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
• We can declare multiple resources just fine in a try-with-resources block by
separating them with a semicolon:
try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}} 40
Custom Exceptions (1)
• It is exception designed by programmer
• Rules to design user defined Exception
v Create a package with valid user defined name.
v Create any user defined class.
v Make that user defined class as derived class of
Exception or RuntimeException class.
v Declare parametrized constructor with string variable.
v call super class constructor by passing string variable
within the derived class constructor.
v Save the program with public class name.java

41
Custom Exceptions (2)
public class InvalidAgeException extends Exception{
InvalidAgeException(String s){ super(s); } }
class TestCustomException1{
static void validate(int age) throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(-1);
}catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
42
Review Questions
1. Explain what try-with-resources with example?
2. Define your own exception to accept a positive number only. i.e. catch negative
numbers as exception.
3. Explain the different types of exceptions in java? Example: A
NumberFormatException can occur when an attempt is made to convert a string into a
number. Such conversions are done by the functions Integer.parseInt and
Integer.parseDouble.
Consider the function call Integer.parseInt(str) where str is a variable of type String. If the
value of str is the string "42", then the function call will correctly convert the string into
the int 42.
However, if the value of str is, say, "Abebe", the function call will fail because "Abebe" is
not a legal string representation of an int value. In this case, an exception of type
NumberFormatException occurs. If nothing is done to handle the exception, the program
will crash.

43
Questions?

44

You might also like