Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
70 views22 pages

OOP - Chapter 4

The document discusses exception handling in Java. It defines what exceptions are, provides examples of exceptions, and explains how Java handles exceptions by searching for catch blocks and throwing exceptions. It also covers exception types and differentiating between exceptions and errors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views22 pages

OOP - Chapter 4

The document discusses exception handling in Java. It defines what exceptions are, provides examples of exceptions, and explains how Java handles exceptions by searching for catch blocks and throwing exceptions. It also covers exception types and differentiating between exceptions and errors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Chapter 4

Exception Handling

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
1
. Exception Handling
 When a program runs into a runtime error, the program terminates
abnormally. How can you handle the runtime error so that the
program can continue to run or terminate gracefully? This is the
subject we will introduce in this topic.

• What is an Exception?
• An exception is an event that occurs during the execution of a program
which interrupts the normal flow of instructions.

• Examples -
1. Divide a number by 0
2. Access an out-of-bounds array element
3. Null Pointer reference
4. Cannot convert a string to an integer
5. .... and lots more.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
2
How Java Handles Exception?
 When an error occurs within a Java method, the
method creates an Exception object and hands it
off to the runtime system.
 The runtime system is then responsible for finding
some code to handle the error.
 In Java terminology, creating an exception object
and handing it to the runtime system is called
throwing an exception.
 After a method throws an exception, the runtime
system will find someone to handle the exception.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
How Java Handles Exception?
void p() {
 The runtime system searches try {
backwards through the call stack to f();
}
find a method that contains an catch (Exception e) {
appropriate exception handler (see // something to do 3
.....
example at the right). }
}
 The exception handler chosen is said to
catch the exception. void f() {
g();
 } 2
If no exception handler is found, the
Java program terminates . void g() {
h();
1
}

void h() {
// error occurs
throw new
Exception();
......
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
4
Why using Exceptions?
 Standardized error handling
policy.
 Separate error handling from
the logic flow (no if-else
statement).
 Force the programmer to handle
the error.
 Can be used in Constructor.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
5
Exception Types
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
6
System Errors
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


System errors are thrown by JVM
and represented in the Error class. LinkageError
The Error class describes internal
system errors. Such errors rarely Error VirtualMachineError
occur. If one does, there is little
you can do beyond notifying the
Many more classes
user and trying to terminate the
program gracefully.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
7
Exceptions
Exception describes errors
caused by your program ClassNotFoundException
and external ArithmeticException
circumstances. These IOException
errors can be caught and Exception NullPointerException
handled by your program.
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
8
Runtime Exceptions
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError
RuntimeException is caused by
programming errors, such as bad
Error VirtualMachineError casting, accessing an out-of-bounds
array, and numeric errors.
Many more classes

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
9
Declaring, Throwing, and
Catching Exceptions

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; }
} }
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
10
Declaring Exceptions
Every method must state the types of checked
exceptions it might throw. This is known as
declaring exceptions.

public void myMethod()


throws IOException

public void myMethod()


throws IOException, OtherException

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
11
Throwing Exceptions
When the program detects an error, the program
can create an instance of an appropriate exception
type and throw it. This is known as throwing an
exception. Here is an example,

throw new TheException();

TheException ex = new TheException();


throw ex;

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
12
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
13
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
14
Catching Exceptions
main method { method1 { method2 { An exception
... ... ... is thrown in
try { try { try { method3
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }

Call Stack
method3

method2 method2

method1 method1 method1

main method main method main method main method

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
15
Order of Exceptions in Catch Block
try { try {
} }

catch (Exception ex) { catch (RuntimeException ex) {


} }
catch (RuntimeException ex) { catch (Exception ex) {
} }

Wrong Order Correct Order

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
16
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
17
Cautions When Using Exceptions
 Exception handling separates error-handling
code from normal programming tasks, thus
making programs easier to read and to modify.
Be aware, however, that exception handling
usually requires more time and resources
because it requires instantiating a new exception
object, rolling back the call stack, and
propagating the errors to the calling methods.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
18
When to Throw Exceptions
 An exception occurs in a method. If you want
the exception to be processed by its caller, you
should create an exception object and throw it.
If you can handle the exception in the method
where it occurs, there is no need to throw it.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
19
When to Use Exceptions
When should you use the try-catch block in the code?
You should use it to deal with unexpected error
conditions. Do not use it to deal with simple, expected
situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
20
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
21
End of Ch_4

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
05/07/2024 rights reserved. 0132130807
22

You might also like