Course List: http://www.c-jump.com/bcc/
Exceptions definition:
an occurrence of an undesirable situation that can be detected during program execution.
The exception-aware program converts such undesirable occurrence into a recognizeable event, and then handles this event to manage the situation.
Examples:
Division by zero
Trying to open an input file that does not exist
An array index that goes out of bounds
The code could use an if statements to handle an exception:
int result = method( parameters ); if ( result == ERROR_CODE_A ) { // handle the problem A } else if ( result == ERROR_CODE_B ) { // handle the problem B } else { // no errors detected }
However, using the if statements may not be the most effective solution:
primarily, because the code that detects the error often cannot handle it;
secondarily, because a large number of error-related ifs will easily
obscure the main flow of the program logic
make the program hard to understand and maintain
introduce new logical problems
The exception mechanism is an object-oriented alternative.
When an exception occurs, an object of a particular exception class is created
Java provides a number of exception classes to handle common exceptions such as division by zero, invalid input format, file open/read/write/close errors.
For example,
When a division by zero exception occurs, the program creates an object of the class ArithmeticException
When a Scanner object attempts data input into a program, an invalid format errors are handled using the class InputMismatchException
The class Exception is (directly or indirectly) the superclass of all the exception classes in Java
Statements that might generate an exception are placed in a try block
Not all statements in the try block will execute; the execution is interrupted if an exception occurs
The try block is followed by
one or more catch blocks
or, if a try block has no catch block, then it must have the finally block
A catch block specifies the type of exception it can catch. It contains the code known as exception handler
The last catch block may be followed by an optional finally block
Any code contained in a finally block always executes, regardless of whether an exception occurs, except when the program exits early from a try block by calling the System.exit() method
If no exception is thrown in a try block, all catch blocks associated with the try block are ignored and program execution resumes after the last catch block
If an exception is thrown in a try block,
the remaining statements in the try block are ignored
The program searches the catch blocks in the order in which they appear after the try block, searching for an appropriate exception handler
If the type of the thrown exception matches the parameter type in one of the catch blocks, the code of that catch block executes and the remaining catch blocks after the matching catch block are ignored
If there is a finally block after the last catch block, the finally block executes regardless of whether an exception occurs.
The heading of a catch block specifies the type of exception it handles
A catch block can catch either
an exception of a specific type
an exception of a subclass of the specified superclass type
any exception, e.g. catch ( Exception ex )
Note: In a sequence of catch blocks, a catch block declaring an exception of a subclass type should be placed before any catch blocks declaring exceptions of a superclass type.
A catch block using the Exception catches all types of exceptions, because Exception is the superclass of all other exceptions. Therefore, it should be placed last in the sequence.
Various exceptions are categorized into separate classes and contained in various packages:
package java.lang;
package java.util;
package java.io;
class Exception
Subclass of class Throwable
Superclass of classes designed to handle exceptions
Various types of exceptions
I/O exceptions
Number format exceptions
File not found exceptions
Array index out of bounds exceptions
See also Java Exception Classes
Each Java program must follow this rule: the code will not compile unless the Catch or Specify requirement is honored. When a block of code can throw an exception, such block of code must be
(a) wrapped by a try statement that catches exceptions and handles them in the corresponding catch blocks (catch)
try { //a block of code that can throw an exception } catch ( ExceptionType ex ) { //... }
(b) enclosed in a method with the throws clause (specify)
public void saveFile() throws IOException {
//a block of code that can throw an exception
}///saveFile
Definition: an exception recognized and detected by the compiler
Example:
FileNotFoundExceptions
Syntax:
modifiers returnType methodName([parameterList]) throws ExceptionType1, ExceptionType2, ... {}
public static void exceptionMethod()
throws InputMismatchException,
FileNotFoundException
{
//statements
}
The method exceptionMethod() throws exceptions of the type InputMismatchException and FileNotFoundException
A reference of a superclass type can point to objects of its subclass
A program can determine if a reference variable points to a specific object type using the instanceof operator.
The catch blocks can be combined with the instanceof checks:
try { //... } catch ( Exception ex ) { if ( ex instanceof ArithmeticException ) { System.out.println( "Exception " + ex.toString() ); } else if ( ex instanceof InputMismatchException ) { System.out.println( "Exception " + ex.toString() ); } }
Definition: exceptions not recognized and not detected when the program compiles.
Unchecked exception are thrown at runtime.
Therefore, to prevent unexpected crashes, the program must employ additional checks for specific conditions, such as
division by zero
array index out of bounds
|
|
Throw the exception to the calling method
Catch the exception and handle it
try {
statements
}
[ catch ( MostSpecificExceptionType ex ) { statements } ] ...
[ catch ( LeastSpecificExceptionType ex ) { statements } ]
[ finally {statements}]
A method that catches two types of exceptions and uses a finally clause
public static String readFirstLine( String path ) { RandomAccessFile in = null; try { in = new RandomAccessFile( path, "r" ); // may throw FileNotFound String line = in.readLine(); // may throw IOException return line; } catch ( FileNotFoundException ex ) { System.out.println( "File not found" ); return null; } catch ( IOException ex ) { System.out.println( "I/O error occurred" ); return null; } finally { try { if ( in != null ) in.close(); // may throw IOException } catch ( Exception ex ) { System.out.println( "Unable to close file." ); } } }
The syntax of the try-with-resources statement
try ( statement[;statement] ... ) { statements } [catch ( MostSpecificExceptionType ex ) { statements } ] ... [catch ( LeastSpecificExceptionType ex ) { statements } ]
A method that catches two types of exceptions and automatically closes the specified resource
public static String readFirstLine( String path ) { try ( RandomAccessFile in = new RandomAccessFile( path, "r" ) ) { String line = in.readLine(); // may throw // IOException return line; } catch ( FileNotFoundException ex ) { System.out.println( "File not found" ); return null; } catch ( IOException ex ) { System.out.println( "I/O error occurred" ); return null; } }
Four methods available from all exceptions
getMessage() toString() printStackTrace() printStackTrace( outputStream )
Determines the order in which the methods were called and where the exception was handled
To print exception data to the error output stream,
try {
//...
}
catch( IOException ex )
{
System.err.println( ex.getMessage() + "\n" );
System.err.println( ex.toString() + "\n" );
ex.printStackTrace();
return null;
}
How to print exception data to the standard output stream
try {
//...
}
catch( IOException ex )
{
System.out.println( ex.getMessage() + "\n" );
System.out.println( ex.toString() + "\n" );
e.printStackTrace( System.out );
return null;
}
The syntax of the multi-catch block
catch ( ExceptionType1 | ExceptionType2 | ExceptionType3 ex ) { //... }
Programming style that does not employ a multi-catch block:
public static String readFirstLine( String path ) { try ( RandomAccessFile in = new RandomAccessFile( path, "r" ) ) { String line = in.readLine(); // may throw // IOException return line; } catch ( FileNotFoundException ex ) { System.err.println( ex.toString() ); return null; } catch ( EOFException ex ) { System.err.println( ex.toString() ); return null; } catch( IOException ex ) { ex.printStackTrace(); return null; } }
Programming style using the multi-catch block:
public static String readFirstLine( String path ) { try ( RandomAccessFile in = new RandomAccessFile( path, "r" ) ) { String line = in.readLine(); // may throw // IOException return line; } catch ( FileNotFoundException | EOFException ex ) { System.err.println( ex.toString() ); return null; } catch( IOException ex ) { ex.printStackTrace(); return null; } }
When an exception occurs in a try block, control immediately passes to one of the catch blocks
Typically, a catch block does one of the following:
Completely handles the exception
Partially processes the exception; in this case, the catch block either
rethrows the same exception for the calling environment to handle the exception
throws another exception for the calling environment to handle the exception
Syntax:
throw exceptionReference; // rethrow throw new anotherException( parameters ); // create and throw new exception
Rethrowing is useful when:
catch block catches exception but is unable to handle it
catch block decides that exception should be handled by the calling environment
throw allows programmer to
provide exception-handling code in one place where it's the most appropriate
The syntax for the declaration of a method that throws exceptions:
modifiers returnType methodName( [parameterList] )
throws exceptionList {}
A method that throws an IOException:
public static long getFileLength() throws IOException
{
RandomAccessFile in =
new RandomAccessFile( path, "r" );
long length = in.length(); // may throw IOException
return length;
}
A method that throws an Exception
public static void myMethod() throws Exception
{
throw new Exception( "Exception generated in myMethod" );
}
}
A method that catches the IOException
public static int getRecordCount2() { try { long length = getFileLength(); // may throw // IOException int recordCount = (int) ( length / RECORD_SIZE ); return recordCount; } catch ( IOException ex ) { System.err.println( "IO error occurred" ); return 0; } }
A method that throws the IOException
public static int getRecordCount3() throws IOException
{
long length = getFileLength(); // may throw
// IOException
int recordCount = (int) ( length / RECORD_SIZE );
return recordCount;
}
Compiler error generated if you don't catch or throw a checked exception
C:\java\netbeans\src\ProductApp.java:12: error: unreported exception IOException; must be caught or declared to be thrown getRecordCount()
The syntax of the throw statement
throw throwableObject;
Common constructors of the Throwable class
Throwable() Throwable( message )
A method that throws an unchecked exception
public double calculateValue(double value) { if ( value <= 0 ) { throw new IllegalArgumentException( "value must be > 0" ); } //... }
import java.util.*;
public class RethrowExceptionExamp1e
{
static Scanner console = new Scanner( System.in );
public static void main( String[] args )
{
int number;
try
{
number = getNumber();
}
catch ( InputMismatchException ex )
{
System.out.println( "Exception " + ex.toString() );
throw ex; //rethrow
}
}
}//class RethrowExceptionExamp1e
Code that throws an IOException for testing purposes
try { // code that reads the first line of a file if ( true ) { throw new IOException( "I/O exception test" ); } return firstLine; } catch ( IOException ex ) { // code to handle IOException goes here }
Code that rethrows an exception
try { // code that throws IOException goes here } catch ( IOException ex ) { System.out.println( "IOException thrown in getFileLength method." ); throw ex; }
When a method requires an exception that isn't provided by any of Java's exception types
When using a built-in Java exception would inappropriately expose details of a method's operation
Constructors of the Throwable class for exception chaining
Throwable( cause ) Throwable( message, cause )
Methods of the Throwable class for exception chaining
getCause() initCause( cause )
A custom exception class that uses exception chaining:
public class MyException extends Exception { public MyException() { } public MyException( Throwable cause ) { super( cause ); } }
Code that throws a MyException with chaining:
catch ( IOException ex ) { throw new MyException( ex ); }
Code that catches MyException and displays the cause:
catch ( MyException ex ) { System.out.println( "MyException: Application Error" ); System.out.println( ex.getCause().toString() ); }
The syntax of the assert statement
assert booleanExpression [: message ];
Code that makes a reasonable assertion about a calculation
assert ( value <= 0 ) : "positive value expected" ;
The output displayed when an assertion exception is thrown:
Exception in thread "main" java.lang.AssertionError: positive value expected at MyApp.calculateValue(MyApp.java:112) at MyApp.main(MyApp.java:27)
Terminate program
Output appropriate error message upon termination
Fix error and continue
Repeatedly get user input
Output appropriate error message until valid value is entered
Log error and continue
Write error messages to file and continue with program execution
Exception class you define extends class Exception or one of its subclasses
Syntax to throw your own exception object:
throw new ExceptionClassName( messageString );
For example,
public class MyDivisionByZeroException extends Exception { public MyDivisionByZeroException() { super( "Cannot divide by zero" ); } public MyDivisionByZeroException( String strMessage ) { super( strMessage ); } }