Sunteți pe pagina 1din 26

Exception Handling and Assertions

Objectives
At the end of the lesson, you should be able to:

• Explain the basic concepts of exception handling.


• Write code to catch and handle exceptions.
• Write code to throw exceptions.
• Create your own exceptions.
• Explain the concepts of assertion.
Exception Handling
 What is an Exception?
 Benefits of Exception Handling
 Exception Class Hierarchy
 Types of Exception
 The Catch or Specify Requirement
 Catching Exceptions with try-catch
 Catching Exceptions with try-catch-finally
 Specifying the Exceptions Thrown by a Method
 Throwing Exceptions
 Creating Your Own Exception Class

What is an Exception?

● Exceptional event
● Error that occurs during runtime
● Cause normal program flow to be disrupted
● Examples
– Divide by zero errors
– Accessing the elements of an array beyond its range
– Invalid input
– Hard disk crash
– Opening a non-existent file
– Heap memory exhausted
Exception: An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions.

When an error occurs within a method, the method creates an object and hands it off to
the runtime system. The object, called an exception object .It contain about the error, including
its type and the state of the program when the error occurred.

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 attempts to find something 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.

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 exception
handler chosen is said to catch the exception.

Benefits of Exception Handling

• Separating Error-Handling code from “regular” business logic code

• Propagating errors up the call stack

• Grouping and differentiating error types


Separating Error-Handling code from “regular” business logic code -In traditional
programming, error detection,reporting, and handling often lead to confusing code.
Exceptions enable you to write the main flow of your code and to deal with the exceptional cases
elsewhere.
Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and
handling errors, but they do help you organize the work more effectively.
Propagating errors up the call stack-A second advantage of exceptions is the ability to
propagate error reporting up the call stack of methods.
For Example, 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. Suppose also that method1 is the only method interested in the errors that might
occur within readFile. Recall that the Java runtime environment searches backward through the
call stack to find any methods that are interested in handling a particular exception. A method
can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to
Exception Class Hierarchy
catch it. Hence, only the methods that care about errors have to worry about detecting errors.
Grouping and differentiating error types-A method can catch an exception based on its group
Theorfigure below illustrates the class hierarchy of the Throwable class and its
general type by specifying any of the exception's superclasses in the catch statement.
most significant subclasses.
Throwable class
– Root class of exception classes
– Subclass of the Object class.
– The objects that inherit from the Throwable class include direct descendants (objects
that inherit directly from the Throwable class) and indirect descendants (objects that
inherit from children or grandchildren of the Throwable class).
checked exception :
These are exceptional conditions that a well-written application should anticipate and
recover from. Checked exceptions are subject to the Catch or Specify Requirement
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. sometimes the user supplies
the name of a nonexistent file, and Types of Exception
the constructor throws java.io.FileNotFoundException. A
well-written program will catch this exception and notify the user of the mistake, possibly
1. Checked Exception.
prompting for a corrected file name.
It occurs in a java program due to invalid user input, network connectivity problem or
database problems.
2. Unchecked Exception.
It occurs because of programming errors, such as invalid arguments passed to a public
method. The java complier does not check the unchecked exceptions during program compilation.
i. Error
ii. Runtime exception
Error: Used by the Java run-time system to handle errors occurring in the run-time
environment.Generally beyond the control of user programs
Examples
● Out of memory errors ● Hard disk crash
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.
Runtime exception : Conditions that user programs can reasonably deal with. Usually the result
of some flaws in the user program code
Examples
● Division by zero error ● Array out-of-bounds error
For example, consider the application described previously that passes a file name to the
The Catch or Specify Requirement
constructor for FileReader. If a logic error causes a null to be passed to the constructor, the
constructor will throw NullPointerException.
• Java code that might throw certain exceptions must be enclosed by either of the following:

o Catching and Handling Exceptions.


• Try block
• Catch block
• Finally block
o Specifying the Exceptions Thrown by a Method.

• Code that fails to honor the Catch or Specify Requirement will not compile.
Try statement that catches the exception. The try must provide a handler for the exception, as
described in Catching and Handling Exceptions.
A method specifies that it can throw the exception. The method must provide a throws clause
that lists the exception, as described in Specifying the Exceptions Thrown by a Method.

Catching Exceptions with try-catch


The try Block:
The first step in constructing an exception handler is to enclose the code that might throw an
exception within a try block.
The catch Blocks:
You associate exception handlers with a try block by providing one or more catch blocks directly
after the try block.
Syntax: Single Exception
try {

} catch (ExceptionType name) { Syntax: Multiple Exceptions


try {
}
} catch (ExceptionType1 name)
{
} catch (ExceptionType 2 name)
{
}
The segment in the example labeled code contains one or more legal lines of code that could
throw an exception.
The programmer can associate exception handlers with a try block by providing atleast one catch
block or finally block, without this we can’t associate exception handler.
Each catch block is an exception handler and handles the type of exception indicated by its
argument. The argument type, ExceptionType, declares the type of exception that the handler can
handle and must be the name of a class that inherits from the Throwable class. The handler can
refer to the exception with name.
The catch block contains code that is executed if and when the exception handler is invoked. The
runtime system invokes the exception handler when the handler is the first one in the call stack
whose ExceptionType matches the type of the exception thrown. The system considers it a match
if the thrown object can legally be assigned to the exception handler's argument.

Example For The try-catch Statements


class DivByZero {
public static void main(String args[]) {
try {
System.out.println(3/0);
System.out.println (“Please print me.”);
} catch (ArithmeticException exc) {
//Division by zero is an ArithmeticException
System.out.println(exc);
}
System.out.println (“After exception.”);
}
}

Example For Multiple catch


class MultipleCatch {
public static void main(String args[]) {
try {
int den = Integer.parseInt(args[0]);
System.out.println(3/den);
} catch (ArithmeticException exc) {
System.out.println(“Divisor was 0.”);
} catch (ArrayIndexOutOfBoundsException exc2) {
System.out.println(“Missing argument.”);
}
System.out.println(“After exception.”);
}
}
Example For Nested try’s
class NestedTryDemo {
public static void main(String args[]){
try {
int a = Integer.parseInt(args[0]);
try {
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println(“Div by zero error!");
}
} catch (ArrayIndexOutOfBoundsException) {
System.out.println(“Need 2 parameters!");
}
}
}
Example For Nested try’s with Method
class NestedTryDemo2 {
static void nestedTry(String args[]) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println("Div by zero error!");
}
}
public static void main(String args[]){
Catching Exceptions with try-catch-finally
try {
nestedTry(args);
The finally Block: } catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Need 2 parameters!");
The finally block always
} executes when the try block exits. This ensures that the finally block is
executed even if an }unexpected exception occurs.
}
Syntax:
try {

} catch (ExceptionType1 name) {

} catch (ExceptionType 2 name) {

} finally {

}
If the JVM exits while the try or catch code is being executed, then the finally block will
not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the
finally block will not execute even though the application as a whole continues.

Note: The finally block is a key tool for preventing resource leaks. When closing a file or
otherwise recovering resources, place the code in a finally block to insure that resource is always
recovered.

Rules for try, catch and finally Blocks :


1. For each try block there can be zero or more catch blocks, but only one finally block.

2. The catch blocks and finally block must always appear in conjunction with a try block.

3. A try block must be followed by either at least one catch block or one finally block.

4. The order exception handlers in the catch block must be from the most specific exception

Example For The try-catch -finally Statements

import java.io.*;
public class ListOfNumbers {
public static void main(String arg[]){
PrintWriter out = null;
try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));
out.println("Example for finally blocks");
} catch (IOException e) {
System.err.println("Caught IOException: "+ e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
}

Specifying the Exceptions Thrown by a Method

• A method is required to either catch or list all exceptions it might throw


– Except for Error or RuntimeException, or their subclasses
• If a method may cause an exception to occur but does not catch it, then it must say so using the
throws keyword
– Applies to checked exceptions only
• Syntax:
<type> <methodName> (<parameterList>) throws <exceptionList> {

<methodBody>

}
The throws statement species the list of exception that has thrown by a method. If a method is
capable of raising an exception that is does not handle, it must specify the exception has to be
handle by the calling method, this is done by using the throw statement.

Example for Exceptions Thrown by a Method:

class ThrowingClass {
static void meth() throws ClassNotFoundException {
throw new ClassNotFoundException ("demo");
}
}
class ThrowsDemo {
public static void main(String args[]) {
try {
ThrowingClass.meth();
} catch (ClassNotFoundException e) {
System.out.println(e);
}
}
}

Output:

java.lang.ClassNotFoundException: demo

Throwing Exceptions

• Java allows you to throw exceptions (generate exceptions)


– throw <exception object>;

• We can also create your own exception classes.


– To represent problems that can occur within the classes you write.

• We can also create chained exceptions.


– An application often responds to an exception by throwing another exception.
All methods use the throw statement to throw an exception. The throw statement requires
a single argument: a throwable object. Throwable objects are instances of any subclass of the
Throwable class.
Chained Exceptions- In effect, the first exception causes the second exception. It can be very
helpful to know when one exception causes another. Chained Exceptions help the programmer
do this. The following example shows how to use a chained exception.
try {

} catch (IOException e) {
throw new SampleException("Other IOException", e);
}

stack trace – It provides information on the execution history of the current thread and lists the
names of the classes and methods that were called at the point when the exception occurred. A
stack trace is a useful debugging tool that you'll normally take advantage of when an exception
has been thrown.

Example for Throwing Exceptions :

class ThrowDemo {
public static void main(String args[]){
String input = “invalid input”;
try {
if (input.equals(“invalid input”)) {
throw new RuntimeException("throw demo");
} else {
System.out.println(input);
}
} catch (RuntimeException e) {
System.out.println("Exception caught:" + e);
}
}
}

Output:
Exception caught: java.lang.RuntimeException: throw demo

Creating Your Own Exception Class

Steps to follow
– Create a class that extends the Exception class
– Customize the class
Members and constructors may be added to the class
Sytntax:
Public class <classname> extends Exception {…..}
Java defines several built-in classes for exception handling. All these classes are a part of
the java.lang package which is automatically imported. That is why, while throwing an exception
you did not specifically include any package for exception classes.
Apart from the built-in exception classes you can define your own exception classes. This
is very useful when you want to define exception types which are having a behavior different
from the standard exception type, particularly when you want to do validations in your
application.
You can create muttiple exceptions for different cirumstances in your code, if your code
access different files. You can throw a different exception for each file.This approach is useful
for several reasons:
• You can handle each exception differently.
• If your exception handlers print out the Exception, this gives you or your users more
information about where the exception occurred.
• You can customize your exception.

Example for Creating Your Own Exception Class

class NumberRangeException extends Exception {


NumberRangeException () {
super("Enter a number between 20 and 100");
}
}
public class My_Exception {
public static void main (String args [ ]) {
try {
int x = 10;
if (x < 20 || x >100) throw new NumberRangeException( );
} catch (NumberRangeException e) {
System.out.println (e);
}
}
}

Assertion
 What are Assertions?
 Compiling Files that useAssertions
 Enabling and Disabling Assertions
 Where You Should Not Use Assertions
 Where It Is Good To Use Assertions
What are Assertions?
• Statements that let a programmer test assumptions about the state of a program.
– Boolean expressions that you believe are true when the assertion executes. If false, system
throws an error.
– By verifying expressions, INCREASE confidence that program is error free.
• Manual approach: Programmer must insert assertions into a program.
• Two forms of the assert statement
– Usualform
Syntax: assert <boolean_expression>;
– Abbreviatedform
Syntax: assert <boolean_expression> : <detail_expression>;
An assertion has a Boolean expression that, if evaluated as false, indicates a bug in the
code. This mechanism provides a way to detect when a program starts falling into an inconsistent
state. Assertions are excellent for documenting assumptions and invariants about a class.
In Usualform, if the Booelan Expression evalutates to false, then an AssertionError is
thrown.This error should not be caught,and the program should be terminated abnormally.
In Abbreviatedform, an assert statement has two parts separated by a colon. The boolean
condition must be true for execution to continue. If it is false, an AssertionError is thrown, which
terminates execution and display the message string.
void noReturn() { }
int aReturn() { return 1; }
void go() {
int x = 1; boolean b = true;
legal assert statements Illegal assert statements
assert(x == 1); assert(x = 1); // none of these are booleans
assert(b); Compiling Files assert(x);
that useAssertions
assert true; assert 0;
assert(x == 1) : x; assert(x == 1) : ; // none of these return a value
assert(x == 1) : aReturn();
• You can use assert as a keyword or as an identifier,
assert(x == 1) : new ValidAssert();
assert(xbut
== not
1) :both.
noReturn();
• The Java 5 compiler will use the assert keyword by default. ValidAssert va;
assert(x == 1) :

Command Line If assert Is an If assert Is a Keyword


Identifier
javac -source 1.3 Code compiles with Compilation fails.
TestAsserts.java warnings.

javac -source 1.4 Compilation fails. Code compiles.


TestAsserts.java
javac -source 1.5 Compilation fails. Code compiles.
TestAsserts.java
javac -source 5 Compilation fails. Code compiles
TestAsserts.java
javac -source 5 Compilation fails. Code compiles
TestAsserts.java
javac Compilation fails. Code compiles
If you want to use assertions, you have to think first about how to compile with assertions
in your code, and then about how to run with assertions enabled.
Identifier vs. Keyword
Prior to version 1.4, you might very well have written code like this:
int assert = getInitialValue();
if (assert == getActualResult()) {
// do something
}
Notice that in the preceding code, assert is used as an identifier. That's not a problem prior to 1.4.
But you cannot use a keyword/reserved word as an identifier, and beginning with version 1.4,
assert is a keyword. Enabling and Disabling Assertions
If you want to tell the compiler to use Java 5 rules you can do one of three things: omit the
• Assertions can be turned-on and off.
-source option, which is the default, or add one of two source options:
– By default, assertions are turned off
• To enable assertions:
java –ea classname java –ea:<package> classname
or
java –enableassertions classname
• To disable assertions:
java –da classname java –da:<class> classname
or
java –disableassertions classname
• To en/disable system assertions: -esa or -dsa
Assertions are typically enabled when an application is being tested and debugged, but disabled
when the application is deployed. The assertions are still in the code, although ignored by the
JVM, so if you do have a deployed application that starts misbehaving, you can always choose to
enable assertions in the field for additional testing.
Selective Enabling and Disabling
The command-line switches for assertions can be used in various ways:
With no arguments (as in the preceding examples) Enables or disables assertions in all
classes, except for the system classes.
java –ea or java –enableassertions java –da or java -disableassertions
With a package name Enables or disables assertions in the package specified, and any
packages below this package in the same directory hierarchy (more on that in a moment).
java -ea:packagename.subpackage……

With a class name Enables or disables assertions in the class specified.


Enable assertions in general, but disable assertions in system classes - java -ea –dsa
Enable assertionsWhere You
in general,but Should
disable Not
assertions Use -Assertions
in package java -ea -da:packagename…

• Do Use Assertions to Validate Arguments to Public Method and Private


Method.
• Do not use assertions to do any work that your application requires for
correct operation.
1. Argument checking is typically part of the published specifications (or contract) of a method,
and these specifications must be obeyed whether assertions are enabled or disabled. Another
problem with using assertions for argument checking is that erroneous arguments should result in
an appropriate runtime exception (such as IllegalArgumentException). An assertion failure will
not throw an appropriate exception.
2. Because assertions may be disabled, programs MUST NOT assume that the boolean
expression contained in an assertion will be evaluated. Violating this rule has dire consequences.
For example, suppose you wanted to remove all of the null elements from a list names, and knew
that the list contained one or more nulls. It would be wrong to do this:
// Broken! - action is contained in assertion
assert names.remove(null);

The program would work fine when asserts were enabled, but would fail when they were
disabled, as it would no longer remove the null elements from the list. The correct idiom is to
perform the action before the assertion and then assert that the action succeeded:
Where It Is Good To Use Assertions
• Internal Invariants
You should now use an assertion whenever you would have written a comment that asserts an
invariant.

An assertion is a switch statement with no default case.

• Control-Flow Invariants
Place an assertion at any location you assume will not be reached

• Preconditions, Postconditions, and Class Invariants


It can help support an informal design-by-contract style of programming.
Internal Invariants : Example
if (i % 3 == 1) { Switch statement
... 1. default:
} else { 2. assert false : suit;
assert i % 3 == 2 : i;
...
}
Control-Flow Invariants : Example
void foo() {
for (...) {
if (...) return;
}
assert false; // Execution should never reach this point!
}
Preconditions, Postconditions, and Class Invariants:
You can test postcondition with assertions in both public and nonpublic methods.
A class invariants is a type of internal invariant that applies to every instance of a class at all
times, except when an instance is in transition from one consistent state to another. A class
invariant can specify the relationships among multiple attributes, and should be true before and
after any method completes.

S-ar putea să vă placă și