Download What Is an Exception?

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Programming
Exception
[email protected]
SCJP 1.5 objectives










Declarations and Access Control
Object Orientation
Assignments
Operators
Flow Control, Exceptions, and Assertions
Strings, I/O, Formatting, and Parsing
Generics and Collections
Inner Classes
Threads
Development
Contents
1.
2.
3.
4.
5.
6.
7.
8.
9.
What Is an Exception?
The Catch or Specify Requirement
Catching and Handling Exceptions
Propagating Uncaught Exceptions
The finally Block
Exception Matching
Specifying the Exceptions Thrown by a Method
FOR SCJP EXAM
Summary
1. What Is an Exception?
 The term exception is shorthand for the phrase "exceptional
event.“
Definition: An exception is an event, which is an
occurrence that alerts the normal program flow.
 When an exceptional event occurs in java, an exception is
said to be “thrown”.
 The code that’s responsible for doing something about the
exception is called an “exception handler” and it “catches”
the thrown exception.
2. The Catch or Specify Requirement
Ex: if you call a method that opens a file but the file cannot be
opened, execution of that method will stop, and code that you
wrote to deal with this situation will be run.
Therefore, we need a way to tell the JVM what code to execute
when a certain exception happens.
 try : define a block of code in which exceptions may occur.
 catch : match a specific exception to block of code that
handles it.
psedocode
1. try {
2.
// This is the first line of the “guarded region”
3.
//that is governed by the try keyword.
4.
//Put code here that might cause some kind of exception.
5.
//We may have many code lines here or just one
6. }
7. catch (FirstException){
8.
// Put code here that handles this exception.
9.
// This is the next line of the exception handler.
10. }
11. catch (SecondException){
12. // Put code here that handles this exception.
13. // This is the next line of the exception handler.
14. }
15.
// Some code here that handles this exception.
psedocode
try {
// do stuff
}catch (SomeException ex){
// do exception handling
}finally {
// clean up
}
try {
// do stuff
}finally {
// clean up
}
try {
// do stuff
}
System.out.println(“out of try block”);
try {
// do stuff
}
System.out.println(“out of try block”);
catch( Exception ex){ }
It is illegal to use a try clause without either a catch clause or a finally clause.
Any catch clauses must immediately follow the try block.
Any finally clause must immediately follow the last catch clause.
The Three Kinds of Exceptions
 Not all exceptions are subject to the Catch (or Specify
Requirement).
 To understand why, we need to look at the three basic
categories of exceptions, only one of which is subject to the
Requirement.
 The Three Kinds of Exceptions
1. checked exception
2. error
3. runtime exception
unchecked exception
Exception Hierarchy
Java.lang.Object
Java.lang.Throwable
Java.lang.Error
Java.lang.Exception
Java.lang.RuntimeException
CheckedException
Example
public class ArrayEx {
public static void main( String[] args ) {
int[] intArray = new int[3];
for( int i=0 ; i<3 ; i++ ) {
intArray[i] = i;
}
intArray[3] = 3;
for( int i=0 ; i<intArray.length ; i++ ) {
System.out.println( intArray[i] );
}
}
}
3. Catching and Handling Exceptions
 This section describes how to use the three exception
handler components — the try, catch, and finally blocks —
to write an exception handler.
public class ArrayEx {
public static void main( String[] args ) {
int[] intArray = new int[3];
for( int i=0 ; i<3 ; i++ ) {
intArray[i] = i;
}
try{
intArray[3] = 3;
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught "
+ "ArrayIndexOutOfBoundsException: " );
}
for( int i=0 ; i<intArray.length ; i++ ) {
System.out.println( intArray[i] );
}
}
}
 Exception handlers can do more than just print error
messages or halt the program.
 They can do error recovery, prompt the user to make a
decision, or propagate the error up to a higher-level handler
using chained exceptions
4. Propagating Uncaught Exceptions
 What happen to an exception that’s thrown in a try block
when there is no catch clause waiting for it?
 If a method doesn’t provide a catch clause for a particular
exception, that method is said to be “ducking” the exception
(or “passing the buck”).
Java method call stack
Ex: If your program stats in method main() and main() calls method a(),
which calls method b(), which in turn calls method c(), the call stack consists
of the {c} , {b} , {a}, {main}.
 1) The call stack while method3() is running.
4
method3()
method2 invokes method3
3
method2()
method1 invokes method2
2
method1()
main invokes method1
1
main()
main begins
The order in which methods are put on the call stack
 2) The call stack after method3() completes
Execution returns to method2()
1
method2()
method2() will complete
2
method1()
method1() will complete
3
main()
main() will complete and the JVM will exit
The order in which methods complete
5. The finally Block
 The finally block always executes when the try block exits.
 This ensures that the finally block is executed even if an
unexpected exception occurs.
 But finally is useful for more than just exception handling
— it allows the programmer to avoid having cleanup code
accidentally bypassed by a return, continue, or break.
 Putting cleanup code in a finally block is always a good
practice, even when no exceptions are anticipated.
psedocode
1. try {
2.
// This is the first line of the “guarded region”
3. }
4. catch (FirstException){
5.
// Put code here that handles this exception.
6. }
7. catch (SecondException){
8.
// Put code here that handles this exception.
9. }
10. finally {
11.
// Put code here to release any resource
12. // we allocated in the try clause.
13.
// More code here
public class Human {
String state = “human";
public void state() {
System.out.println( “I am human." );
}
}
public class Man extends Human
{ class Woman extends Human {
public
String name = “shine";
String name = “chojo";
// return the variable, name
public String getName() {
return name;
}
}
// return the variable, name
public String getName() {
return name;
}
// method overriding
// method overriding
public void state() {
public void state() {
System.out.println( name + “isSystem.out.println(
a man" );
name + “is a wom
}
}
}
public class ClassCast {
public static void main( String[] args ) {
// create Woman object
Woman gemini = new Woman();
// Polymorphism
Human wo = new Woman();
// call method to return name
System.out.println( gemini.getName() );
String wName = ((Woman)wo).getName();
System.out.println( wName );
// class casting
//Man john = (Man)gemini;
Man john = (Man)wo;
// print name
String mName = john.getName();
System.out.println( mName );
}
}
public class ClassCastHandling {
public static void main( String[] args ) {
Woman gemini = new Woman();
Human wo = new Woman();
// call method to return name
System.out.println( gemini.getName() );
String wName = ((Woman)wo).getName();
System.out.println( wName );
// class casting
//Man john = (Man)gemini;
try {
Man john = (Man)wo;
// print names
String mName = john.getName();
System.out.println( mName );
} catch ( ClassCastException cc ) {
//System.out.println( "Message1 : " + cc.getMessage() );
//cc.printStackTrace();
System.out.println( "Message2 : " + cc.toString() );
} finally {
System.out.println( “A man cannot be a woman" );
}
}
}
6. Exception Matching
 When an exception is thrown, Java will try to find a catch
clause for the exception type.
 If it doesn’t find one, it will search for a handler for a
supertype of the exception.
 If it doesn’t find a catch clause for supertype for the
exception, then the exception is propagated down the call
stack.
public class MultiException {
public static void main( String[] args ) {
int value = 20;
int div = 0;
int[] intArray = { 1, 2, 3 };
String s = null;
int result = value / div;
System.out.println( result );
int arrayValue = intArray[4];
System.out.println( arrayValue );
String newString = s.substring( 1, 4 );
System.out.println( newString );
}
}
public class MultiExceptionHandling {
public static void main( String[] args ) {
int value = 20;
int div = 0;
int[] intArray = { 1, 2, 3 };
String s = null;
try {
int result = value / div;
System.out.println( result );
int arrayValue = intArray[4];
System.out.println( arrayValue );
String newString = s.substring( 1, 4 );
System.out.println( newString );
} catch ( ArithmeticException ae ) {
System.out.println( ae.toString() );
} catch ( ArrayIndexOutOfBoundsException ai ) {
ai.printStackTrace();
} catch ( NullPointerException ne ) {
System.out.println( ne.getMessage() ); }} }
 Resist the temptation to write a single catchall exception
handler such as the following:
try {
// some code
}catch (Exception e) {
e.printStackTrace();
}
This code will catch every exception generated. Of course, no
single exception handler can properly handle every exception,
and programming in this way defeats the design objective.
Exception handlers that trap many errors at once will probably
reduce the reliability of your program because it's likely that
an exception will be caught that the handler does not know how
to handle.
import java.io.*;
public class ReadData {
public static void main(String args[]) {
try {
RandomAccessFile raf =
new RandomAccessFile("myfile.txt", "r");
byte b[] = new byte[1000];
raf.readFully(b, 0, 1000);
}catch (FileNotFoundException e) {
System.err.println("File not found");
System.err.println(e.getMessage());
e.printStackTrace();
}catch (IOException e) {
System.err.println("IO Error");
System.err.println(e.toString());
e.printStackTrace();
}
}
}
 Notice that the catch clause for the FileNotFoundException
was placed above the handler for the IOException. This is
really important! If we do it the opposite way, the program
will not compile.
try {
// do risky IO things
} catch (IOException e) {
// handle general IOExceptions
} catch (FileNotFoundException ex) {
// handle just FileNotFoundException
}
7.Specifying the Exceptions Thrown by a Method
 The previous section : how to write an exception handler
 In other cases, however, it's better to let a method further up
the call stack handle the exception.
 The list of thrown exceptions is part of a method's public
interface. The throws keyword is used as follows to list the
exceptions that a method can throw:
void myFunction() throws MyException1, MyException2 {
// code for the method here
}
public class ThrowsException {
public void occurException() throws ArithmeticException {
int result = 3/0;
System.out.println( result );
}
public static void main( String[] args ) {
ThrowException te = new ThrowException();
te.occurException();
}
}
public class ThrowsExceptionHandling {
public void occurException() throws ArithmeticException {
int result = 3/0;
1
System.out.println( result );
2
}
public static void main( String[] args ) {
ThrowsExceptionHandling1 te = new ThrowsExceptionHandling1();
try {
3
te.occurException();
} catch ( ArithmeticException ae ) {
System.out.println( "Exception happens: " + ae.toString() );
System.out.println( “cannot divide by 0" );
} } }
public class ThrowsExceptionHandling2 {
public void occurException() throws ArithmeticException {
1
int result = 3/0;
System.out.println( result );
}
2
public static void main( String[] args ) throws ArithmeticException {
ThrowsExceptionHandling2 te = new ThrowsExceptionHandling2();
te.occurException();
}
}
3
4
JVM
public class ThrowException {
public void exceptionMethod() throws ArrayIndexOutOfBoundsException {
int[] intA = { 1, 2, 3, 4 };
for( int i=0 ; i<10 ; i++ ) {
if( i == 4 ) throw new ArrayIndexOutOfBoundsException();
System.out.println( intA[i] );
}}
public static void main( String[] args ) {
ThrowException te = new ThrowException();
try {
te.exceptionMethod();
} catch ( ArrayIndexOutOfBoundsException ab ) {
System.out.println( “overflow the index” );
ab.printStackTrace();
}}}
RuntimeException
 Suppose your method doesn't directly throw an exception, but calls a
method that does.
 You can choose not to handle the exception yourself and instead just
declare it, as though it were your method that actually throws the
exception.
 If you do declare the exception that your method might get from another
method, and you don't provide a try/catch for it, then the method will
propagate back to the method that called your method, and either be
caught there or continue on to be handled by a method further down the
stack.
 RuntimeException subclasses are exempt, so the compiler won't check
to see if you've declared them.
 But all non-RuntimeExceptions are considered "checked" exceptions.
FOR SCJP EXAM
int value = 20;
int div = 0;
int[] intArray = { 1, 2, 3 };
String s = null;
int result = value / div;
System.out.println( result );
int arrayValue = intArray[4];
System.out.println( arrayValue );
String newString = s.substring( 1, 4 );
System.out.println( newString );
Common Exceptions and Errors
ArrayIndexOutOfBoundsException, ClassCastException,
IllegalArgumentException, IllegalStateException,
NullPointerException, NumberFormatException,
AssertionError, ExceptionInInitializerError,
StackOverflowError, or NoClassDefFoundError.
 Understand which of these are thrown by the virtual
machine and recognize situations in which others should be
thrown programmatically.
Where Exceptions Come From
 JVM exceptions
• Those exceptions or errors that are either exclusively or
most logically thrown by the JVM.
 Programmatic exceptions
• Those exceptions that are thrown explicitly by application
and/or API programmers.
A Summary of the Exam's Exceptions and Errors
Exception
Description
Typically
Thrown
ArrayIndexOutOfBounds
Exception
Thrown when attempting to access an array with
an invalid index value (either negative or beyond
the length of the array).
By the JVM
Thrown when attempting to cast a reference
variable to a type that fails the IS-A test.
By the JVM
Thrown when attempting to access an object
with a reference variable whose current value is
null.
By the JVM
Thrown when attempting to initialize a static
variable or an initialization block.
By the JVM
Typically thrown when a method recurses too
deeply. (Each invocation is added to the stack.)
By the JVM
Thrown when the JVM can’t find a class it
needs, because of a command-line error, a
classpath issue, or a missing .class file.
By the JVM
ClassCastException
NullPointerException
ExceptionInInitializerError
StackOverflowError
NoClassDefFoundError
A Summary of the Exam's Exceptions and Errors
Exception
Description
Typically
Thrown
IllegalArgument
Exception
Thrown when a method receives an argument fo
rmatted differently than the method expects.
Programmat
ically
Thrown when the state of the environment doesn
’t match the operation being attempted, e.g., usin
IllegalStateException
g a Scanner that’s been closed.
Programmat
ically
Thrown when a method that converts a String to
a number receives a String that it cannot convert.
Programmat
ically
Thrown when a statement’s boolean test returns
false.
Programmati
cally
NumberFormat
Exception
AssertionError
Exercise
 Make exception handling code
• Case1 : j =0
• Case2 : i or j - not a number
• Case3 : num of the parameter is not 2
class ArgDiv {
public static void main(String args[]) {
System.out.println("Input 2 numbers");
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
System.out.println("Division result = " +
i/j);
}
}
Summary

A program can use exceptions to indicate that an error occurred. To throw an exception,
use the throw statement and provide it with an exception object — a descendant of
Throwable — to provide information about the specific error that occurred. A method
that throws an uncaught, checked exception must include a throws clause in its
declaration. A program can catch exceptions by using a combination of the try, catch,
and finally blocks.
1.
The try block identifies a block of code in which an exception can occur.
2.
The catch block identifies a block of code, known as an exception handler, that can
handle a particular type of exception.
3.
The finally block identifies a block of code that is guaranteed to execute, and is the
right place to close files, recover resources, and otherwise clean up after the code
enclosed in the try block.

The try statement should contain at least one catch block or a finally block and may
have multiple catch blocks.

The class of the exception object indicates the type of exception thrown. The exception
object can contain further information about the error, including an error message. With
exception chaining, an exception can point to the exception that caused it, which can in
turn point to the exception that caused it, and so on.