Lecture - 10& 11:exception Handling: CSEC 313: Object - Oriented Programming
Lecture - 10& 11:exception Handling: CSEC 313: Object - Oriented Programming
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
throw
To throw an exception, you use the throw keyword. The
primary formula of using this keyword is:
try {
Normal flow
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
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.
Questions?