Chapter 17
Responding to Abnormal Conditions
17.1 Background
- An exception is a representation of an error or an unexpected condition.
- Exceptions are notified by objects of special exception classes.
class prg {
public static void main ( String [] args ){
int i = 1;
i = i / 0;
} }
// Run time error:
// Exception in thread "main" java.lang.ArithmeticException: / by zero
// at prg.main(a.java:4)
17.2 Exception Catching
- The exception conditions can be handled by try/catch blocks:
try { <code> }
catch ( <exception parameter> ) { <respond> }
..........
catch ( <exception parameter> ) { <respond> }
try { i = 1 / 0; }
catch (java.lang.ArithmeticException ae){
System.out.println( "error: division by 0" );
}
- An abnormal termination of the try block transfers the control out with an object of the exception type.
- The first catch fragment, having the parameter type of the exception object, is executed.
17.3 Exception Forwarding
Exercises
17.4 Assignment #22: Exceptions
Due: skip
The given program uses a single-parameter method ‘repoertType’ that, when provided an argument of type
String, reports whether or not the argument can be parsed to a value of type byte.
Modify the ‘reportType’ method so that it will report for each primitive numeric type whether or not the argument
can be parsed to a value of that type.
The program should provide an output of the following form.
byte short int long float double
123
123 123 123 123 123.0 123.0
1234
no 1234 1234 1234 1234.0 1234.0
123456
no no 123456 123456 123456.0 123456.0
12345678901
no no no 12345678901 1.23456788E10 1.2345678901E10
12345678901234567890
no no no no 1.2345679E19 1.2345678901234567E19
1.2e34
no no no no 1.2E34 1.2E34
1.2e123
no no no no Infinity 1.2E123
1.2e345
no no no no Infinity Infinity
abc
no no no no no no
lab22.java
class lab22 {
public static void main (String [] args) {
print( "byte", 7 ); print( "short", 6 ); print( "int", 8 );
print( "long", 13 ); print( "float", 15 ); print( "double", 23 );
System.out.println();
reportType("123");
reportType("1234");
reportType("123456");
reportType("12345678901");
reportType("12345678901234567890");
reportType("1.2e34");
reportType("1.2e123");
reportType("1.2e345");
reportType("abc");
}
static void reportType( String s ){
System.out.println( s );
try{ byte bb = Byte.parseByte( s );
print( "" + bb, 7 );
} catch( java.lang.NumberFormatException be ){
print( "no", 7 );
}
System.out.println();
}
static void print ( String s, int n){
String f = s;
int i;
for( i=0; i<n; i++ ){ f = " " + f; }
i = f.length();
f = f.substring( i-n );
System.out.print( f );
}
}
Assume ‘lab22’ for the submit program, and submit the lab22.java file.
Note: Files that fail to compile, and execute when applicable, will not be examined. They will be awarded a grade
of 0 points.