42
Java Programming Exception [email protected]

Java Programming Exception

  • Upload
    melia

  • View
    44

  • Download
    0

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: Java Programming Exception

Java Programming Exception

[email protected]

Page 2: Java Programming Exception

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

Page 3: Java Programming Exception

Contents

1. What Is an Exception?

2. The Catch or Specify Requirement

3. Catching and Handling Exceptions

4. Propagating Uncaught Exceptions

5. The finally Block

6. Exception Matching

7. Specifying the Exceptions Thrown by a Method

8. FOR SCJP EXAM

9. Summary

Page 4: Java Programming Exception

1. What Is an Exception?

The term exception is shorthand for the phrase "exceptional event.“

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.

Definition:  An exception is an event, which is an occurrence that alerts the normal program flow.Definition:  An exception is an event, which is an occurrence that alerts the normal program flow.

Page 5: Java Programming Exception

2. The Catch or Specify Requirement

try : define a block of code in which exceptions may occur. catch : match a specific exception to block of code that

handles it.

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.

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.

Page 6: Java Programming Exception

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 one6. }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.

Page 7: Java Programming Exception

psedocode

try { // do stuff}finally { // clean up}

try { // do stuff}catch (SomeException ex){ // do exception handling}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.

Page 8: Java Programming Exception

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 exceptionunchecked exception

Page 9: Java Programming Exception

Exception Hierarchy

Java.lang.Object

Java.lang.Throwable

Java.lang.Error Java.lang.Exception

Java.lang.RuntimeException CheckedException

Page 10: Java Programming Exception

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] );

}}

}

Page 11: Java Programming Exception

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.

Page 12: Java Programming Exception

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] );}

}}

Page 13: Java Programming Exception

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

Page 14: Java Programming Exception

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”).

Page 15: Java Programming Exception

Java method call stack

1) The call stack while method3() is running.

The order in which methods are put on the 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}.

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}.

method3()

method2()

method1()

main()

4

3

2

1

method2 invokes method3

method1 invokes method2

main invokes method1

main begins

Page 16: Java Programming Exception

2) The call stack after method3() completes

Execution returns to method2()

The order in which methods complete

method2()

method1()

main()

1

2

3

method2() will complete

method1() will complete

main() will complete and the JVM will exit

Page 17: Java Programming Exception

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.

Page 18: Java Programming Exception

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

Page 19: Java Programming Exception

public class Human {String state = “human";

public void state() {System.out.println( “I am human." );

}}

public class Human {String state = “human";

public void state() {System.out.println( “I am human." );

}}

public class Man extends Human {String name = “shine";

// return the variable, namepublic String getName() {

return name;}

// method overridingpublic void state() {

System.out.println( name + “is a man" );}

}

public class Man extends Human {String name = “shine";

// return the variable, namepublic String getName() {

return name;}

// method overridingpublic void state() {

System.out.println( name + “is a man" );}

}

public class Woman extends Human {String name = “chojo";

// return the variable, namepublic String getName() {

return name;}

// method overridingpublic void state() {

System.out.println( name + “is a woman" );}

}

public class Woman extends Human {String name = “chojo";

// return the variable, namepublic String getName() {

return name;}

// method overridingpublic void state() {

System.out.println( name + “is a woman" );}

}

Page 20: Java Programming Exception

public class ClassCast {public static void main( String[] args ) {

// create Woman objectWoman gemini = new Woman();// PolymorphismHuman wo = new Woman();

// call method to return nameSystem.out.println( gemini.getName() );String wName = ((Woman)wo).getName();System.out.println( wName );

// class casting//Man john = (Man)gemini;Man john = (Man)wo;// print nameString mName = john.getName();System.out.println( mName );

}}

Page 21: Java Programming Exception

public class ClassCastHandling { public static void main( String[] args ) {

Woman gemini = new Woman();Human wo = new Woman();

// call method to return nameSystem.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" );} } }

Page 22: Java Programming Exception
Page 23: Java Programming Exception

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.

Page 24: Java Programming Exception

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 );

}}

Page 25: Java Programming Exception

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() ); }} }

Page 26: Java Programming Exception

try {

// some code

}catch (Exception e) {e.printStackTrace();

}

Resist the temptation to write a single catchall exception handler such as the following:

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.

Page 27: Java Programming Exception

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();

} }}

Page 28: Java Programming Exception

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}

Page 29: Java Programming Exception

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}

Page 30: Java Programming Exception

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();

}

}

Page 31: Java Programming Exception

public class ThrowsExceptionHandling {

public void occurException() throws ArithmeticException {

int result = 3/0;

System.out.println( result );

}

public static void main( String[] args ) {

ThrowsExceptionHandling1 te = new

ThrowsExceptionHandling1();

try {

te.occurException();

} catch ( ArithmeticException ae ) {

System.out.println( "Exception happens: " +

ae.toString() );

System.out.println( “cannot divide by 0" );

} } }

1

2

3

Page 32: Java Programming Exception

public class ThrowsExceptionHandling2 {

public void occurException() throws ArithmeticException {

int result = 3/0;System.out.println( result );

}

public static void main( String[] args ) throws ArithmeticException {

ThrowsExceptionHandling2 te = new ThrowsExceptionHandling2();

te.occurException();}

}JVM

1

2

34

Page 33: Java Programming Exception

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();

}}}

Page 34: Java Programming Exception

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.

Page 35: Java Programming Exception

FOR SCJP EXAM

Page 36: Java Programming Exception

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 );

Page 37: Java Programming Exception

Common Exceptions and Errors

Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programmatically.

ArrayIndexOutOfBoundsException, ClassCastException,

IllegalArgumentException, IllegalStateException,

NullPointerException, NumberFormatException,

AssertionError, ExceptionInInitializerError,

StackOverflowError, or NoClassDefFoundError.

Page 38: Java Programming Exception

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.

Page 39: Java Programming Exception

A Summary of the Exam's Exceptions and Errors

Exception DescriptionTypically

Thrown

ArrayIndexOutOfBoundsException

Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array).

By the JVM

ClassCastExceptionThrown when attempting to cast a reference variable to a type that fails the IS-A test.

By the JVM

NullPointerException

Thrown when attempting to access an object with a reference variable whose current value is null.

By the JVM

ExceptionInInitializerErrorThrown when attempting to initialize a static variable or an initialization block.

By the JVM

StackOverflowErrorTypically thrown when a method recurses too deeply. (Each invocation is added to the stack.)

By the JVM

NoClassDefFoundError

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

Page 40: Java Programming Exception

A Summary of the Exam's Exceptions and Errors

Exception DescriptionTypically

Thrown

IllegalArgument

Exception Thrown when a method receives an argument formatted differently than the method expects.

Programmati

cally

IllegalStateException

Thrown when the state of the environment doesn’t match the operation being attempted, e.g., using a Scanner that’s been closed.

Programmati

cally

NumberFormat

Exception

Thrown when a method that converts a String to a number receives a String that it cannot convert.

Programmati

cally

AssertionErrorThrown when a statement’s boolean test returns false.

Programmatically

Page 41: Java Programming Exception

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);

}}

Page 42: Java Programming Exception

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.