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

Chapter 4 Exceptions Short Lecture

This document discusses exception handling in Java. It defines three categories of exceptions: checked exceptions, runtime exceptions, and errors. Checked exceptions must be declared or handled, runtime exceptions do not need to be declared, and errors indicate serious problems and cannot typically be recovered from. The document then discusses Java's exception hierarchy and some common exceptions. It explains that exception handling in Java uses try, catch, throw, throws and finally keywords. Code that might cause an exception is placed in a try block, and catch blocks handle specific exceptions. Finally blocks contain cleanup code that always executes.

Uploaded by

Behaylu Addisu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Chapter 4 Exceptions Short Lecture

This document discusses exception handling in Java. It defines three categories of exceptions: checked exceptions, runtime exceptions, and errors. Checked exceptions must be declared or handled, runtime exceptions do not need to be declared, and errors indicate serious problems and cannot typically be recovered from. The document then discusses Java's exception hierarchy and some common exceptions. It explains that exception handling in Java uses try, catch, throw, throws and finally keywords. Code that might cause an exception is placed in a try block, and catch blocks handle specific exceptions. Finally blocks contain cleanup code that always executes.

Uploaded by

Behaylu Addisu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 39

Introduction

 There are three categories of errors: syntax errors, runtime


errors, and logic errors.
Syntax errors:- arise because the rules of the language have
not been followed. They are detected by the compiler.
Runtime errors:- occur while the program is running if the
environment detects an operation that is impossible to carry
out.
Logic errors:- occur when a program doesn't perform the
way it was intended to.
 This chapter introduces using exception handling to deal
with
runtime
2
error.
Introduction
An exception is a problem that arises during the
execution of a 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) ……
Introduction…
Some of these exceptions are caused by
 user error,
 programmer error,
physical resources
A well-designed program should include code to guard
against errors and other exceptional conditions when
they arise.
In Java, the preferred way of handling such conditions is
to use exception handling - a divide-and-conquer
approach that separates a program's normal code from
its error-handling code.
Java's Exception Hierarchy
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
Java's Exception Hierarchy
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.
Some Common Exceptions…
Categories of Exception
To understand how exception handling works in Java,
you 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.
Categories of Exception…
Runtime exceptions:(unchecked exc)
 Runtime exception is an exception that occurs due
programmer error?
As opposed to checked exceptions, runtime exceptions
are ignored at the time of compilation.
RuntimeException 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.
Categories of Exception…

 Errors are thrown by JVM and represented in the


Error
class. The Error class describes internal system errors.
Runtime Exception, Error and their subclasses are
known as
unchecked exceptions.

10
Exception Handling

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.
Exception Handling
Traditional way of Handling Errors
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?
}
Exception Handling…
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
for (int k = 1; k <= N; k++) into the algorithm
sum += k;
return sum/N; // What if N is 0?
} // avgFirstN()
Some Common Exceptions
EXCEPTIONS DESCRIPTION CHECKED UNCHECKED

Arithmetic errors such as a


ArithmeticException YES
divide by zero
ArrayIndexOutOfBoundsExceptio Arrays index is not within
YES
n array.length
Related Class not found.
Attempt to use a class that does
not exist. This exception would
occur, for example, if you tried
ClassNotFoundException to run a nonexistent class using YES
the java command, or is your
program was composed of, say,
three class files, only two of
which could be found.
Related to input/output
operations such as invalid input,
reading past the end of a file, and
opening a nonexistent file.
IOException Examples of subclass of YES
IOException are
InterruptedIOException,
EOFException and
FileNotFoundException.
A method is passed an argument
IllegalArgumentException that is Illegal and inappropriate YES
when calling a method
One thread has been interrupted
InterruptedException YES
by another thread
NoSuchMethodException Nonexistent method YES
Attempt to access an object
NullPointerException YES
through a null reference variable.
Invalid string for conversion to
NumberFormatException YES
number
Exception handling…
How do you handle exceptions?

Java exception handling is managed via five


keywords: try, catch, throw, throws, and finally.

Exception handling is accomplished through the


“try – catch” mechanism, or by a “throws or
throw” clause in the method declaration.
Exception handling…
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 arise is placed in a block of code starting with
the “catch” keyword.
A try/catch block is placed around the code that
might generate an exception.
Exception handling…
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.
Exception handling…
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
Exception handling…
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 no exceptions arise during the execution of the
try block, the catch blocks are skipped.
Exception handling…

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
Exception handling…
Exception handling…
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);
}
23 }
Exception handling…
Exception handling…
Example:
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");
}
}
Exception handling…

try { try {
..….. ..…..
} }
catch(Exception ex){ catch(RuntimeException ex){
……. ……
} }
catch (RuntimeException ex) { catch (Exception ex ) {
…….. ……..
} }

(a) Wrong order (b) Correct Order


Exception handling…
The finally Keyword
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:
Exception handling…
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
}
Exception handling…

• The finally block always executed regardless an


exception or not except 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
Exception handling…
Example:

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");
}
}
}
Exception handling…

Output:

Exception thrown:java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Exception handling…
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.
Exception handling…
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.
Exception handling…
• 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
Exception handling…
 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.

35
Exception handling…
Example
Suppose that method p1 invokes method p2 and p2 may
throw a checked exception (e.g., IOException).

void p1() { void p1() throws IOException {


try { p2();
p2(); }
}
catch (IOException ex) {
...
}
}

36
Exception handling…
Getting Information from Exception
 An Exception object contains valuable information
about the exception. You may use the following
instance methods in the java.lang.Throwable class
to get information regarding the exception.

public String getMessage()


Returns the message of this object or null if there is
no detail message.
Exception handling…
public String toString()
Returns the concatenation of three strings:

public void printStackTrace()


Prints theThrowable object and its call stack trace
information on the console.u can get better
information
Creating a better error message for debugging:
e.printStackTrace()…

As a final point - don't forget the e.getMessage()


method - because the error message is not
automatically printed to the screen.

You might also like