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

Lecture - 10& 11:exception Handling: CSEC 313: Object - Oriented Programming

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.

Uploaded by

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

Lecture - 10& 11:exception Handling: CSEC 313: Object - Oriented Programming

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.

Uploaded by

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

CSEC 313: Object – Oriented Programming

Lecture – 10& 11 :Exception


Handling

Uttam Kumar Dey


What is an Exception?

The term exception is shorthand for the phrase


"exceptional event."

Definition: An exception is an event, which occurs


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

After a method throws an exception, the runtime


system attempts to find something to handle it. The
set of possible "somethings" to handle the exception
is the ordered list of methods that had been called to
get to the method where the error occurred. The list
of methods is known as the call stack.
What is an Exception?
• The runtime system searches the call stack for a
method that contains a block of code that can handle
the exception. This block of code is called an exception
handler. The search begins with the method in which
the error occurred and proceeds through the call stack
in the reverse order in which the methods were called.
When an appropriate handler is found, the runtime
system passes the exception to the handler. An
exception handler is considered appropriate if the type
of the exception object thrown matches the type that
can be handled by the handler.
What is an Exception?
The exception handler chosen is said to catch the
exception. If the runtime system exhaustively searches all
the methods on the call stack without finding an
appropriate exception handler, as shown in the next figure,
the runtime system (and, consequently, the program)
terminates.
The Three Kinds of Exceptions
Checked exception : The first kind of exception is the
checked exception. These are exceptional conditions that
a well-written application should anticipate and recover
from. For example, suppose an application prompts a
user for an input file name, then opens the file by passing
the name to the constructor for java.io.FileReader.
Normally, the user provides the name of an existing,
readable file, so the construction of the FileReader object
succeeds, and the execution of the application proceeds
normally. But sometimes the user supplies the name of a
nonexistent file, and the constructor throws
java.io.FileNotFoundException. A well-written program
will catch this exception and notify the user of the
mistake, possibly prompting for a corrected file name.
The Three Kinds of Exceptions

Checked exceptions are subject to the Catch or Specify


Requirement. All exceptions are checked exceptions, except
for those indicated by Error, RuntimeException, and their
subclasses.
Error: The second kind of exception is the error. These are
exceptional conditions that are external to the application,
and that the application usually cannot anticipate or
recover from. For example, suppose that an application
successfully opens a file for input, but is unable to read the
file because of a hardware or system malfunction. The
unsuccessful read will throw java.io.IOError. An application
might choose to catch this exception, in order to notify the
user of the problem — but it also might make sense for the
program to print a stack trace and exit.
The Three Kinds of Exceptions

Errors are not subject to the Catch or Specify Requirement.


Errors are those exceptions indicated by Error and its
subclasses.
Runtime exception: The third kind of exception is the
runtime exception. These are exceptional conditions that
are internal to the application, and that the application
usually cannot anticipate or recover from. These usually
indicate programming bugs, such as logic errors or improper
use of an API. For example, consider the application
described previously that passes a file name to the
constructor for FileReader. If a logic error causes a null to be
passed to the constructor, the constructor will throw
NullPointerException. The application can catch this
exception, but it probably makes more sense to eliminate
the bug that caused the exception to occur.
The Three Kinds of Exceptions

Runtime exceptions are not subject to the Catch or Specify


Requirement. Runtime exceptions are those indicated by
RuntimeException and its subclasses.

Errors and runtime exceptions are collectively known as


unchecked exceptions.
Catching and Handling Exceptions

Java exception handling is managed via five keywords:


try, catch, throw, throws, and finally.
• Program statements that you want to monitor for
exceptions are contained within a try block.
• If an exception occurs within the try block, it is thrown.
Your code can catch this exception (using catch) and
handle it in some rational manner.
• System-generated exceptions are automatically thrown
by the Java run-time system. To manually throw an
exception, use the keyword throw.
• Any exception that is thrown out of a method must be
specified as such by a throws clause.
• Any code that absolutely must be executed after a try
block completes is put in a finally block.
Catching and Handling Exceptions

General form of an exception-handling block:


try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has
occurred.
Catching and Handling Exceptions

The most common types of exceptions


1. NullPointerException: generated when the reference
used to invoke a method has value null, or when
we try to access an instance variable through a null
reference. Some methods throw explicitly this type
of exception when they are passed a parameter that is
null.
2. ArrayIndexOutOfBoundsException: generated when
we access an element of an array using an index
that is less than zero, or bigger than the length of the
array minus one.
3. IOException: generated by methods that access
input/output devices when an error situation occurs.
4. FileNotFoundException: generated when we try to
open a non-existent file.
Catching and Handling Exceptions

5. NumberFormatException: generated by methods that


perform conversions from strings to numbers.
Forexample, Integer.parseInt generates an exception of
this type if the string passed as parameter does
not contain a number.
Catching and Handling Exceptions

class Example1 {
public static void main(String[] args) {
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
//
// try block
try {
result = a / b;
System.out.println("Result = " + result);
}
// catch block
catch (ArithmeticException e) {
//
} }}
Catching and Handling Exceptions

Example2:
Multiple catch blocks
class Example2
{
public static void main(String[] args) {
try {
int arr[]={1,2};

} catch(ArithmeticException ae) {

}
catch(ArrayIndexOutOfBoundsException e) {

}
}}
Catching and Handling Exceptions

Example of unreachable catch block


class Excep{
public static void main(String[] args) {
try {
//
} catch(Exception e) // This block handles all
Exception
{
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) {
//This block is unreachable
}
}}
Catching and Handling Exceptions

Nested try: try statement can be nested inside another


block of try. Nested try block is used when a part of a
block may cause one error while entire block may cause
another error. In case if inner try block does not have a
catch handler for a particular exception then the outer try
is checked for match.
class Excep{
public static void main(String[] args) {
try {
//
try {
//
} catch(ArithmeticException ae) {
System.out.println("divide by zero");
}
//
} catch(ArrayIndexOutOfBoundsException e) {
// } }}
Catching and Handling Exceptions

throw
To throw an exception, you use the throw keyword. The
primary formula of using this keyword is:
try {
Normal flow

When to throw the exception


throw What?
}
catch(Exception e) {
// Deal with the exception here
}
The new keyword in this formula is throw. On the right
side of throw, indicate to the compiler what to do. This
means that the throw keyword is followed by an
expression.
Catching and Handling Exceptions

Advantages of Exceptions
Advantage 1: Separating Error-Handling Code from
"Regular" Code
Exceptions provide the means to separate the details of
what to do when something out of the ordinary
happens from the main logic of a program. In traditional
programming, error detection, reporting, and handling
often lead to confusing spaghetti code. For example,
consider the pseudocode method here that reads an
entire file into memory.
Handling Exceptions

Advantage 2: Propagating Errors Up the Call Stack


A second advantage of exceptions is the ability to propagate
error reporting up the call stack of methods. Suppose that
the readFile method is the fourth method in a series of
nested method calls made by the main program: method1
calls method2, which calls method3, which finally calls
readFile.
method1 {
call method2;
}
method2 {
call method3;
}
method3 {
call readFile;
}
Handling Exceptions

Advantage 3: Grouping and Differentiating Error Types


Because all exceptions thrown within a program are objects,
the grouping or categorizing of exceptions is a natural
outcome of the class hierarchy. An example of a group of
related exception classes in the Java platform are those
defined in java.io — IOException and its descendants.
IOException is the most general and represents any type of
error that can occur when performing I/O. Its descendants
represent more specific errors. For example,
FileNotFoundException means that a file could not be
located on disk.
A method can write specific handlers that can handle a very
specific exception. The FileNotFoundException class has no
descendants, so the following handler can handle only one
type of exception.
Handling Exceptions

catch (FileNotFoundException e) {
...
}
A method can catch an exception based on its group or
general type by specifying any of the exception's
superclasses in the catch statement. For example, to catch all
I/O exceptions, regardless of their specific type, an exception
handler specifies an IOException argument.
catch (IOException e) {
...
}
This handler will be able to catch all I/O exceptions, including
FileNotFoundException, EOFException, and so on. You can
find details about what occurred by querying the argument
passed to the exception handler. For example, use the
following to print the stack trace.
Handling Exceptions

Summary
A program can use exceptions to indicate that an error
occurred. To throw an exception, use the throw statement and
provide it with an exception object — a descendant of
Throwable — to provide information about the specific error
that occurred. A method that throws an uncaught, checked
exception must include a throws clause in its declaration.

A program can catch exceptions by using a combination of the


try, catch, and finally blocks.

The try block identifies a block of code in which an exception


can occur.
The catch block identifies a block of code, known as an
exception handler, that can handle a particular type of
exception.
Handling Exceptions

The finally block identifies a block of code that is guaranteed


to execute, and is the right place to close files, recover
resources, and otherwise clean up after the code enclosed in
the try block.
The try statement should contain at least one catch block or
a finally block and may have multiple catch blocks.

The class of the exception object indicates the type of


exception thrown. The exception object can contain further
information about the error, including an error message.
With exception chaining, an exception can point to the
exception that caused it, which can in turn point to the
exception that caused it, and so on.
Handling Exceptions

Questions?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy