DSC 6 10

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 56

Exception Handling in Java

DSC-6-10
Handling
An condition that arises in a code sequence at run time, In other words, an
exception is a run-time error.

In computer languages that do not support exception handling, errors


exception is an abnormal must be checked and handled manually—typically
through the use of error codes, and so on.

This approach is as cumbersome as it can create troubles in handling errors.

Java’s exception handling avoids these problems and, in the process, brings
run-time error management into the object-oriented world.
Exceptions
Origin:
Unexpected conditions

Disrupt normal flow of program

With exception handling, we can develop more robust programs

Exceptions are thrown, And can be caught.

Either JVM OR Java Programs – can throw an exception


Exceptions
When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error.

That method may choose to handle the exception itself, or pass it on.

Either way, at some point, the exception is caught and processed.

Exceptions can be generated by the Java run-time system, or they can be manually
generated by our code.

Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java
language or the constraints of the Java execution environment.
Exceptions Types
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


System Errors
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes


System errors are thrown by JVM and
represented in the Error class.
VirtualMachineError
The Error class describes internal systemError
errors, Such errors rarely occur. AWTError

If one does, there is little we can do


beyond notifying the user and trying to Several more classes

terminate the program gracefully.


Exceptions
Exception describes errors caused by ClassNotFoundException
your program and external
circumstances.
IOException
ArithmeticException
Exception AWTException
These errors can be caught and handled
NullPointerException
by your program.
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


7
Runtime Exceptions

ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
RuntimeException is caused by
AWTError
programming errors, such as bad
casting, accessing an out-of-bounds
Several more classes array, and numeric errors.
Types of Exceptions
• Errors - serious and fatal problems

• Exceptions - can be thrown by any program, user can extend

• RuntimException - caused by illegal operations, thrown by JVM


(unchecked)

9
Checked Exceptions vs. Unchecked Exceptions
RuntimeException, Error and their subclasses are known as
unchecked exceptions.
All other exceptions are known as checked exceptions - the
compiler forces the programmer to check and deal with the
exceptions.
Checked or Unchecked Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
Unchecked
AWTError
exception.

Several more classes


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

12
Exceptions
Exception handling is managed via five keywords: try, catch, throw, throws, and finally.

Program statements that we want to monitor for exceptions are contained within a try
block, if an exception occurs within the try block, it is thrown.

The 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
try-catch
Default exception handling is useful for debugging, you will usually want to handle an
exception yourself, doing so provides two benefits:

First, it allows you to fix the error, and Second, it prevents the program from automatically
terminating.

Sometimes a program stops running and prints a stack trace whenever an error occurs, it is
quite easy to prevent this using the try block.

Immediately following the try block, include a catch clause that specifies the exception
type that you wish to catch.
try-catch
class Exc2 {
public static void main(String args[]) {
int d, a;

try { // monitor a block of code.


d = 0;
a = 42 / d;
}

catch (ArithmeticException e) {
// catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
throw
We catch exceptions that are thrown by the Java run-time system, However, it is possible
for your program to throw an exception explicitly, using the throw statement.

The general form of throw is shown here: throw ThrowableInstance;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

Primitive types, such as int or char, as well as non-Throwable classes, such as String and
Object, cannot be used as exceptions.

There are two ways you can obtain a Throwable object: using a parameter in a catch
clause, or creating one with the new operator.
throw
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed.

The nearest enclosing try block is inspected to see if it has a catch statement that matches
the type of exception.

If it does find a match, control is transferred to that statement, If not, then the next
enclosing try statement is inspected, and so on.

If no matching catch is found, then the default exception handler halts the program and
prints the stack trace.
throw
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
}
catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
}
catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}}}
throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.

We do this by including a throws clause in the method’s declaration.

A throws clause lists the types of exceptions that a method might throw.

This is necessary for all exceptions, except those type Error or RuntimeException, or any of
their subclasses.

All other exceptions that a method can throw must be declared in the throws clause, If
they are not, a compile-time error will result.
finally
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path
that alters the normal flow through the method.

Depending upon how the method is coded, it is even possible for an exception to cause
the method to return prematurely.

This could be a problem in some methods, for example, if a method opens a file upon
entry and closes it upon exit, then you will not want the code that closes the file to be
bypassed by the exception-handling mechanism.

The finally keyword is designed to address this contingency, it creates a block of code that
will be executed after a try/catch block has completed and before the code following the
try/catch block.
finally
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch statement matches
the exception.

Any time a method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed just
before the method returns.

This can be useful for closing file handles and freeing up any other resources that might
have been allocated at the beginning of a method with the intent of disposing of them
before returning.
The finally clause is optional. However, each try statement requires at least one catch or a
finally clause.
Checked Exceptions
Checked exceptions that can be thrown in a method must be
• caught and handled
OR
• declared in the throws clause

22
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

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

24
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");

}
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;
}
Catch or Declare Checked Exceptions
If a method declares a checked exception, you must invoke it in a try-catch block
or declare to throw the exception in the calling method.

In this example, 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) { }
...
}
}

(a) (b)
27
Exceptions in GUI Applications
The methods are executed on the threads, If an exception occurs on a thread, the
thread is terminated if the exception is not handled.
However, the other threads in the application are not affected, there are several
threads running to support a GUI application.

A thread is launched to execute an event handler (e.g., the actionPerformed


method for the ActionEvent).

If an exception occurs during the execution of a GUI event handler, the thread is
terminated if the exception is not handled.

Java prints the error message on console, but does not terminate the application.
The program goes back to its user-interface-processing loop to run continuously.
28
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

29
animation
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

30
animation
Trace a Program Execution

The final block is


try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

31
animation
Trace a Program Execution

Next statement in the


try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

32
animation
Trace a Program Execution

try { Suppose an exception


statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

33
animation
Trace a Program Execution

try { The exception is


statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

34
animation
Trace a Program Execution

try { The final block is


statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

35
animation
Trace a Program Execution

try { The next statement in


statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

36
animation
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
37
animation
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
38
animation
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
39
animation
Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3; transferred to the caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;
40
Cautions When Using Exceptions
• Exception handling separates error-handling code from
normal programming tasks, thus making programs
easier to read and to modify.
• 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.

41
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.

42
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");
}
43
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");

44
Creating Custom Exception Classes

 Use the exception classes in the API whenever possible.


 Create custom exception classes if the predefined
classes are not sufficient.
 Declare custom exception classes by extending
Exception or a subclass of Exception.

45
Exceptions and Generics
• A generic class cannot extend Throwable.
• An Exception cannot be of a generic type.

46
Exceptions and Inheritance
How do you think exceptions affect overridden methods?
• if a method overrides a base class method, the new method cannot
throw a more general error, but can throw more specific
• if the base class method throws no errors, the subclass method can't
either.

47
Assertions
An assertion is a Java statement that enables you
to assert an assumption about your program.

An assertion contains a Boolean expression that


should be true during program execution.

Assertions can be used to assure program


correctness and avoid logic errors.

48
Declaring Assertions
An assertion is declared using the new Java keyword
assert in JDK 1.4 as follows:

assert assertion; or
assert assertion : detailMessage;

where assertion is a Boolean expression and


detailMessage is a primitive-type or an Object value.

49
Assertions
• If an assertion evaluates true, there are no effects.

• If an assertion fails, AssertionError is thrown.

50
Executing Assertions Example
public class AssertionDemo {
public static void main(String[] args) {
int i; int sum = 0;
for (i = 0; i < 10; i++) {
sum += i;
}
assert i == 10;
assert sum > 10 && sum < 5 * 10 : "sum is " + sum;
}
}

51
Running Programs with Assertions
By default, the assertions are disabled at runtime. To
enable it, use the switch –enableassertions, or –ea for
short, as follows:

java –ea AssertionDemo

Assertions can be selectively enabled or disabled at


class level or package level. The disable switch is –
disableassertions or –da for short. For example, the
following command enables assertions in package
package1 and disables assertions in class Class1.
java –ea:package1 –da:Class1 AssertionDemo
52
Assertions
Use assertions for verification:
• preconditions: beginning of method body
• postconditions: before each return statement
• invariants of class: entry and exit points of public methods

• Good for debugging.

53
Using Exception Handling or
Assertions
Assertion should not be used to replace exception handling.

Exception handling addresses robustness and assertion addresses


correctness.

Like exception handling, assertions are not used for normal tests, but
for internal consistency and validity checks.

Assertions are checked at runtime and can be turned on or off at


startup time.

54
Using Exception Handling or
Assertions, cont.
Use assertions to reaffirm assumptions. This gives you
more confidence to assure correctness of the program.
A common use of assertions is to replace assumptions
with assertions in the code.

55
Using Exception Handling or
Assertions, cont.
Another good use of assertions is place assertions in a
switch statement without a default case. For example,

switch (month) {
case 1: ... ; break;
case 2: ... ; break;
...
case 12: ... ; break;
default: assert false : "Invalid month: " + month
}

56

You might also like