Documente Academic
Documente Profesional
Documente Cultură
Objectives
At the end of the lesson, you should be able to:
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.
• 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.
} 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.
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
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");
}
}
}
}
<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.
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
} 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.
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
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.
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) :
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.
• Control-Flow Invariants
Place an assertion at any location you assume will not be reached