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

December 8, 2021 Exception Handling in Java 1

Exceptions represent errors or unexpected situations that can occur during program execution. The Java language includes built-in exceptions and supports exception handling using try-catch blocks and throws clauses. A try-catch block encapsulates code that might throw an exception within a try block, and provides catch blocks to handle specific exception types. Exceptions can be either handled locally using try-catch or propagated to other methods using throws.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

December 8, 2021 Exception Handling in Java 1

Exceptions represent errors or unexpected situations that can occur during program execution. The Java language includes built-in exceptions and supports exception handling using try-catch blocks and throws clauses. A try-catch block encapsulates code that might throw an exception within a try block, and provides catch blocks to handle specific exception types. Exceptions can be either handled locally using try-catch or propagated to other methods using throws.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29

Exception Handling in Java

December 8, 2021 Exception Handling in Java 1


Exception Handling in Java
• Topics:
– Introduction
– Errors and Error handling
– Exceptions
– Types of Exceptions
– Coding Exceptions
– Summary

December 8, 2021 Exception Handling in Java 2


Introduction
• Users have high expectations for the code
we produce.
• Users will use our programs in unexpected
ways.
• Due to design errors or coding errors, our
programs may fail in unexpected ways
during execution

December 8, 2021 Exception Handling in Java 3


Introduction
• It is our responsibility to produce quality
code that does not fail unexpectedly.
• Consequently, we must design error
handling into our programs.

December 8, 2021 Exception Handling in Java 4


Errors and Error Handling
• An Error is any unexpected result obtained from
a program during execution.
• Unhandled errors may manifest themselves as
incorrect results or behavior, or as abnormal
program termination.
• Errors should be handled by the programmer, to
prevent them from reaching the user.

December 8, 2021 Exception Handling in Java 5


Errors and Error Handling
• Some typical causes of errors:
– Memory errors (i.e. memory incorrectly
allocated, memory leaks, “null pointer”)
– File system errors (i.e. disk is full, disk has
been removed)
– Network errors (i.e. network is down, URL
does not exist)
– Calculation errors (i.e. divide by 0)

December 8, 2021 Exception Handling in Java 6


Errors and Error Handling
• More typical causes of errors:
– Array errors (i.e. accessing element –1)
– Conversion errors (i.e. convert ‘q’ to a
number)
– Can you think of some others?

December 8, 2021 Exception Handling in Java 7


Errors and Error Handling
• Exceptions – a better error handling
• Exception handling (EH) allows a
programmer to provide code in the program
to handle run-time errors or exceptional
situations
– this improves reliability

December 8, 2021 Exception Handling in Java 8


Exceptions
• What are they?
– An exception is a representation of an error
condition or a situation that is not the
expected result of a method.
– Exceptions are built into the Java language
and are available to all program code.
– Exceptions isolate the code that deals with
the error condition from regular program logic.

December 8, 2021 Exception Handling in Java 9


Exceptions
• How are they used?
– Exceptions fall into two categories:
• Checked Exceptions
• Unchecked Exceptions
– Checked exceptions are inherited from the core Java
class Exception. They represent exceptions that are
frequently considered “non fatal” to program
execution
– Checked exceptions must be handled in your code, or
passed to parent classes for handling.

December 8, 2021 Exception Handling in Java 10


Exceptions
• How are they used?
– Unchecked exceptions represent error
conditions that are considered “fatal” to
program execution.
– You do not have to do anything with an
unchecked exception. Your program will
terminate with an appropriate error message.

December 8, 2021 Exception Handling in Java 11


Exceptions
• Examples:
– Checked exceptions include errors such as
“array index out of bounds”, “file not found”
and “number format conversion”.
– Unchecked exceptions include errors such as
“null pointer”.

December 8, 2021 Exception Handling in Java 12


Exceptions
• How do you handle exceptions?
– Exception handling is accomplished through
the “try – catch” mechanism, or by a “throws”
clause in the method declaration.
– For any code that throws a checked
exception, you can decide to handle the
exception yourself, or pass the exception “up
the chain” (to a parent class).

December 8, 2021 Exception Handling in Java 13


Exceptions
• How do you handle exceptions?
– To handle the exception, you write a “try-catch” block.
To pass the exception “up the chain”, you declare a
throws clause in your method or class declaration.
– If the method contains code that may cause a
checked exception, you MUST handle the exception
OR pass the exception to the parent class
(remember, every class has Object as the ultimate
parent)

December 8, 2021 Exception Handling in Java 14


Coding Exceptions
• 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.

December 8, 2021 Exception Handling in Java 15


Coding Exceptions
• Try-Catch Mechanism
– 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)

December 8, 2021 Exception Handling in Java 16


Coding Exceptions
• Example
– try {
… normal program code
}
catch(Exception e) {
… exception handling code
}

December 8, 2021 Exception Handling in Java 17


Coding Exceptions
• Passing the exception
– In any method that might throw an exception,
you may declare the method as “throws” that
exception, and thus avoid handling the
exception yourself
– Example
• public void myMethod throws IOException {
… normal code with some I/O
}

December 8, 2021 Exception Handling in Java 18


Coding Exceptions
• Types of Exceptions
– All checked exceptions have class
“Exception” as the parent class.
– You can use the actual exception class or the
parent class when referring to an exception
– Where do you find the exception classes?
• Reference books such as “Java in a Nutshell”
(O’Reilly, 2001), or the Java Documentation.

December 8, 2021 Exception Handling in Java 19


Coding Exceptions
• Types of Exceptions
– Examples:
• public void myMethod throws Exception {
• public void myMethod throws IOException {
• try { … }
catch (Exception e) { … }
• try { … }
catch (IOException ioe) { … }

December 8, 2021 Exception Handling in Java 20


Code Examples
• 1. Demonstration of an unchecked
exception (NullPointerException)
• 2. Demonstration of checked exceptions:
– Passing a DivideByZeroException
– Handling a DivideByZeroException

December 8, 2021 Exception Handling in Java 21


Summary
– Exceptions are a powerful error handling
mechanism.
– Exceptions in Java are built into the language.
– Exceptions can be handled by the
programmer (try-catch), or handled by the
Java environment (throws).

December 8, 2021 Exception Handling in Java 22


Exception Handling
The try / catch blocks
try {
//statements – one of which is capable of throwing an exception
}
catch (ExceptionTypeName objName) {
//one or more statements to execute if this exception occurs
}
finally {
//statements to be executed whether or not exception occurs
}
Encapsulate statement or statements that can throw an exception in
One
a try
Each
An or moreblock
block.
optional
catch catch
finallyblocks
blockmust
specifies the immediately
cantype
be added follow
of exception
at the thataofit
end try
theblock
catchto
handles in
provide
a blocks error
parameter handling
to provide
list. a setroutines for anythat
of statements exceptions thatexecuted
are always occur
while executing
whether or nottheanstatements in the try block.
exception occurs.
December 8, 2021 Exception Handling in Java 23
Exception Handling
The exception hierarchy (partial)

Exception

DataFormatException IOException RunTimeException

NumberFormatException
EOFException FileNotFoundException InterruptedIOException

All
Common
exceptions
IOException Exception
caninherit sub
fromclasses
be decomposeda base
intoinclude:
class Exception
specific classes of I/O errors
NumberFormatException
December 8, 2021 is a Handling
Exception subclass of DataFormatException
in Java 24
Exception Handling
Example
Consider implementing the BufferReader readLine( ) example with
try-catch clocks.
import java.io.*
public class ExceptionalExample {
public static void main(String [ ] args) //no throws clause used here
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println(“Enter a number”);
try {
try block encapsulates
String str = br.readLine( ); the readLine( ) method
double num = Double.parseDouble(str); and the conversion from
}
December 8, 2021 Exception Handling in Javaif str
String to double. 25
Will throw NumberFormatException
cannot be converted to a double.
Exception Handling
Example (continued)

//add the catch blocks


catch (IOException ioe) { catch the IOException object
thrown by readLine( )
//print a message to the screen
System.out.println(ioe.toString( )); Note! ioe is a handle
} (reference) to an IOException
object thrown by readLine( )
catch (Exception e) {
//catch any other exception and print a message to the screen
System.out.println(e.toString( ));
}
Note! toString( ) is a method that all
finally {
Classes inherit (implicitly).
System.exit(0); In the finally clause we ensure that the
program terminates
Since both properly
catch blocks – exit(0)
have signifies
the same
} normal termination.
implementation
December 8, 2021 Exception Handling in Java in this example, there is no need
26
to single out IOException in a separate block.
Exceptions – Examples

• FileNotFoundException ( java.io )
– Request to open file fails
• IllegalArgumentException ( java.lang )
– Method passed illegal / inappropriate argument
• IOException ( java.io )
– Generic I/O error
• NullPointerException ( java.lang )
– Attend to access object using null reference
• UnsupportedOperationException ( java.lang )
– Object does not provide requested operation

December 8, 2021 Exception Handling in Java 27


Generating & Handling
Exceptions
• Java primitives
– Try
– Throw
– Catch
– Finally
• Procedure for using exceptions
1. Enclose code generating exceptions in try block
2. Use throw to actually generate exception
3. Use catch to specify exception handlers
4. Use finally to specify actions after exception
December 8, 2021 Exception Handling in Java 28
Example
• Java how to program sixth addition

December 8, 2021 Exception Handling in Java 29

You might also like