java exceptions

43
Java Exceptions Java Exceptions

Upload: vincenzo-deegan

Post on 02-Jan-2016

53 views

Category:

Documents


0 download

DESCRIPTION

Java Exceptions. Exceptions. Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: A program tries to open a file which does not exist. A disk drive fails when a program is trying to read from it. An attempt is made to divide by zero. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Java Exceptions

Java ExceptionsJava Exceptions

Page 2: Java Exceptions

ExceptionsExceptions

Often in computing, operations Often in computing, operations cannot properly execute because cannot properly execute because some sort of error has occurred. some sort of error has occurred. Some examples:Some examples:– A program tries to open a file which A program tries to open a file which

does not exist.does not exist.– A disk drive fails when a program is A disk drive fails when a program is

trying to read from it.trying to read from it.– An attempt is made to divide by zero.An attempt is made to divide by zero.

Page 3: Java Exceptions

Traditional WaysTraditional Ways

An exception is an indication that something went wrong in a An exception is an indication that something went wrong in a program. Traditionaly, error checking is tangled with the program. Traditionaly, error checking is tangled with the code that provides normal functionality.code that provides normal functionality.…………

if(num != 0)if(num != 0){{ result = 100/num;result = 100/num;}}elseelse{{ //print error//print error //get new value//get new value //do more stuff//do more stuff}}…………

Page 4: Java Exceptions

Java ExceptionsJava Exceptions

The error checking and recovery breaks The error checking and recovery breaks up the flow of normal processing.up the flow of normal processing.

Removing error checking and recovery Removing error checking and recovery from the normal flow of a program will:from the normal flow of a program will:– Make code easier to readMake code easier to read– Make code easier to writeMake code easier to write

Exception handling allows programmers Exception handling allows programmers to handle exceptional cases outside the to handle exceptional cases outside the normal flow of control.normal flow of control.

Page 5: Java Exceptions

Addition ExampleAddition Example

We saw earlier that our Addition We saw earlier that our Addition class did not catch possible class did not catch possible exceptions. exceptions. – Invoking Integer.parseInt(String) Invoking Integer.parseInt(String)

resulted in a resulted in a NumberFormatException if the string NumberFormatException if the string provided did not represent a valid provided did not represent a valid integer.integer.

Page 6: Java Exceptions

Catching Exception Catching Exception (Easy way)(Easy way)

... try { number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null,“Input ERROR”); System.exit(0); } sum = number1 + number2; JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); System.exit( 0 ); // terminate the program...

Page 7: Java Exceptions

Catching Exception Catching Exception (Better way)(Better way)

...boolean inputOK = false;while (!inputOK) { inputOK = true; firstNumber = JOptionPane.showInputDialog("Enter first integer" ); try { number1 = Integer.parseInt( firstNumber ); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, “Input ERROR!”); inputOK = false; } }… < same for secondNumber > …

Page 8: Java Exceptions

Exception HierarchyException Hierarchy

Page 9: Java Exceptions

Java ErrorsJava Errors

In Java the Error class defines serious In Java the Error class defines serious errors that the programmer should errors that the programmer should not even attempt to recover from.not even attempt to recover from.

Typical Errors are:Typical Errors are:– Virtual Machine ErrorsVirtual Machine Errors– Out of memoryOut of memory– Stack overflowStack overflow– Windowing ErrorWindowing Error

Page 10: Java Exceptions

Java ExceptionsJava Exceptions

In Java the Exception class defines In Java the Exception class defines mild error conditions that your mild error conditions that your programs might encounter.programs might encounter.

Rather than blindly terminating the Rather than blindly terminating the program, you can write code to handle program, you can write code to handle your exceptions and continue your exceptions and continue executing the program.executing the program.

RunTimeExceptionRunTimeException Other type of Exceptions (We call them Other type of Exceptions (We call them

Non RunTimeException)Non RunTimeException)

Page 11: Java Exceptions

Typical exceptionsTypical exceptions

– The file you are trying to open doesn’t The file you are trying to open doesn’t existexist

– The network connection is disruptedThe network connection is disrupted– The user entered invalid dataThe user entered invalid data– The numeric values you are manipulating The numeric values you are manipulating

are out of the prescribed rangeare out of the prescribed range– Trying to use an uninitialized referenceTrying to use an uninitialized reference– Going outside the bounds of an arrayGoing outside the bounds of an array

Page 12: Java Exceptions

try/catchtry/catch

try/catch blocks are used to catch and handle try/catch blocks are used to catch and handle exceptionsexceptionstrytry{{

… … //normal flow of program//normal flow of program}}catch(Exceptiontype reference)catch(Exceptiontype reference){{

… … //exception handler code//exception handler code}}

Page 13: Java Exceptions

try/catchtry/catch

If an exception occurs within a try If an exception occurs within a try block, all catch blocks will be block, all catch blocks will be searched for a matching exception searched for a matching exception type.type.

The keyword The keyword throwthrow is used to throw is used to throw an exceptionan exceptionthrow new ExceptionType();throw new ExceptionType();

The exception can be thrown from The exception can be thrown from within a method and be handled by within a method and be handled by the caller.the caller.

Page 14: Java Exceptions

try/catchtry/catch

Catch blocks specify different Catch blocks specify different types (All derived from types (All derived from ‘Throwable’) of exceptions.‘Throwable’) of exceptions.

If an exception is caught, the flow If an exception is caught, the flow of control will enter the catch of control will enter the catch block.block.

Once the block is done executing, Once the block is done executing, flow of control will pick up after flow of control will pick up after the last catch block the last catch block

Page 15: Java Exceptions

try/catchtry/catch

If an exception is not caught If an exception is not caught locally, the next enclosing locally, the next enclosing try/catch block will be tested.try/catch block will be tested.

The order of enclosing try/catch The order of enclosing try/catch blocks will follow the call stack.blocks will follow the call stack.

Page 16: Java Exceptions

finallyfinally

The The finallyfinally statement defines a block of code that statement defines a block of code that always executes regardless of whether an always executes regardless of whether an exception was caught.exception was caught.

trytry{//protected code{//protected code startFaucet();startFaucet(); waterLawn();waterLawn();}}catch(Exception e)catch(Exception e){{ //handle exception//handle exception}}finallyfinally{{ stopFaucet();stopFaucet();}}

Page 17: Java Exceptions

What need to be done for What need to be done for the three types of the three types of exceptionsexceptions There are two types of exceptions in Java:There are two types of exceptions in Java:

– RuntimeException- indicates a design or RuntimeException- indicates a design or implementation problem that occurs because the implementation problem that occurs because the programmer made a mistake. This should never programmer made a mistake. This should never happen if the program is running properly. Not happen if the program is running properly. Not required by compiler to be handled. Programmer is required by compiler to be handled. Programmer is encouraged to handle thoughencouraged to handle though

– Non-RuntimeException- indicates difficulty at Non-RuntimeException- indicates difficulty at runtime. File not present, user enters invalid data. runtime. File not present, user enters invalid data. must be checked, either handled or propagatemust be checked, either handled or propagate

Page 18: Java Exceptions

Common ExceptionsCommon Exceptions

– ArithmeticExceptionArithmeticException– NullPointerExceptionNullPointerException– NegativeArraySizeExceptionNegativeArraySizeException– ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException– SecurityExceptionSecurityException– IOExceptionIOException

Page 19: Java Exceptions

Handle or Declare RuleHandle or Declare Rule

Java requires that if an Non Java requires that if an Non RunTimeException occurs while a RunTimeException occurs while a method is executing the caller must method is executing the caller must determine what action is to be taken.determine what action is to be taken.

There are two things that can be done There are two things that can be done by the callerby the caller– Enclose the method call in a try/catch blockEnclose the method call in a try/catch block– Indicate that the calling method will not Indicate that the calling method will not

handle the exceptionhandle the exception

Page 20: Java Exceptions

Handle or Declare RuleHandle or Declare Rule

To indicate that the calling method will To indicate that the calling method will not handle the exception use the not handle the exception use the keyword keyword throwsthrows in the method in the method definition.definition.public void foo() throws ExceptionTypepublic void foo() throws ExceptionType

This indicates that foo will not handle the This indicates that foo will not handle the exception, but whoever called foo will.exception, but whoever called foo will.

This rule only applies for exceptions This rule only applies for exceptions derived from Exception but not derived derived from Exception but not derived from RuntimeExceptionfrom RuntimeException

Page 21: Java Exceptions

Try, Catch, FinallyTry, Catch, Finally

trytry

tryblocktryblock

catch catch (exception_type identifie(exception_type identifier)r)

catchblockcatchblock

catch catch (exception_type identifie(exception_type identifier)r)

catchblockcatchblock

......... // 0 or more of these......... // 0 or more of these

finally // 0 or 1 of thesefinally // 0 or 1 of these

finallyblockfinallyblock

Page 22: Java Exceptions

Try, Catch and FinallyTry, Catch and Finally

Execute tryblock of statements until either an Execute tryblock of statements until either an exception is thrown or the block finishes exception is thrown or the block finishes successfully.successfully.

If an exception is thrown, the catch clauses are If an exception is thrown, the catch clauses are examined in order, to find one for an exception of examined in order, to find one for an exception of the thrown class or one of the thrown classes the thrown class or one of the thrown classes superclasses.superclasses.

If none are found, propagate the exception to a If none are found, propagate the exception to a surrounding try block, and if needed to the calling surrounding try block, and if needed to the calling method.method.

The finally block is always executed, even if no The finally block is always executed, even if no exceptions are thrown.exceptions are thrown.

Page 23: Java Exceptions

Another Another try/catchtry/catch exampleexample

public static String readString(){ int ch; String r = ""; boolean done = false; while (!done) { try { ch = System.in.read(); /* try block */

if (ch < 0 || (char)ch == `\n’) done = true;

else r = r + (char) ch; } catch(IOException e) /* catch clause */ { done = true; /* } handler code */ }; return r;}

Page 24: Java Exceptions

Propagating an Propagating an ExceptionException

if you call a method that throws a if you call a method that throws a checked exception, you must either checked exception, you must either handle it or propagate it.handle it or propagate it.

propagate an propagate an Exception Exception by adding a by adding a throw clausethrow clause in the method header in the method header

Page 25: Java Exceptions

ExampleExample

public static String readString() throws IOException{ int ch; String r =""; boolean done = false; while (!done) { ch = System.in.read(); if (ch < 0 || (char)ch == `\n’) done = true;

else r = r + (char) ch; }; return r;}

Page 26: Java Exceptions

Finally ExampleFinally Examplepublic boolean searchFor(String file, String word)public boolean searchFor(String file, String word)

throws StreamException {throws StreamException {

try {try {

input = new Stream(file);input = new Stream(file);

while (!input.eof())while (!input.eof())

if ((input.next()).equals(word))if ((input.next()).equals(word))

return true; //word foundreturn true; //word found

return false; //word not foundreturn false; //word not found

}}

finally { finally {

////finally finally block is executed whether or not block is executed whether or not try try throws an exception. throws an exception.

if (input != null)if (input != null)

input.close(); }}input.close(); }}

Page 27: Java Exceptions

Exception not caughtException not caught

If an exception occurs and is not If an exception occurs and is not caught (in a non-graphical caught (in a non-graphical application) Java will terminate the application) Java will terminate the program, and display a message program, and display a message and a stack trace to the console.and a stack trace to the console.

printStackTrace()printStackTrace() getMessage()getMessage()

Page 28: Java Exceptions

main() {main() {

fie();fie();

}}

fie() {fie() {

foo();foo();

}}

foo() {foo() {

int i=1;int i=1;

int j=0;int j=0;

i = i/j;i = i/j;

}}

Divide by 0 exception thrown.

Runtime looks for an enclosing try..catch statement in foo().

Runtime then looks for enclosing try... catch statement in method which called foo(): fie().

Runtime than looks for enclosing try... catch statement in method which called fie(): main().

If exception not caught when it leaves your program, the default catch is used which returns an error message.

Page 29: Java Exceptions

Throwing ExceptionThrowing Exception

Exceptions are thrown (signaled) whenExceptions are thrown (signaled) when– you make a programming error (system you make a programming error (system

throws an exception implicitly.) throws an exception implicitly.) – you call a method that throws an you call a method that throws an

exception.exception.– you detect an error and throw an you detect an error and throw an

exception explicitly.exception explicitly.– an internal error occurs in Java. an internal error occurs in Java. (Error (Error

Class)Class)

Page 30: Java Exceptions

Example 1Example 1

class ImplicitThrow {class ImplicitThrow {

public static main(String[ ] args) {public static main(String[ ] args) {

int i = 1, j=0, k;int i = 1, j=0, k;

k= i/j;k= i/j;

System.out.println("k is " + k);System.out.println("k is " + k);

}}}}

Throws an Throws an ArithmeticException ArithmeticException Unchecked Unchecked exceptions need not be declaredexceptions need not be declared

Page 31: Java Exceptions

Example 2Example 2

class MethodThrows {class MethodThrows {

public Image loadImage(String source)public Image loadImage(String source)

throws MalformedURLException, IOException {throws MalformedURLException, IOException {

URL url = new URL(source);URL url = new URL(source);

InputStream in = url.openStream()InputStream in = url.openStream()

}}

}} Throws Throws MalformedURLException, IOExceptionMalformedURLException, IOException Method Must declare checked exceptionsMethod Must declare checked exceptions

Page 32: Java Exceptions

Explicitly Throw an Explicitly Throw an Exception Exception

Find an appropriate exception class from Find an appropriate exception class from the API (or define your own by the API (or define your own by subclassing subclassing ExceptionException))

create an object of that classcreate an object of that class throw itthrow it Thrown exceptions dealt with by calling Thrown exceptions dealt with by calling

method. This declaration forces calling method. This declaration forces calling method to catch exception or propagate method to catch exception or propagate it.it.

Rethrow?Rethrow?

Page 33: Java Exceptions

Example 3Example 3

String readInput (BufferedReader in) throws EOFException /* throw clause */{ . . . while (. . .) { if (ch == -1) /* EOF encountered */ { if (n < len) throw new EOFException(); } . . . } return s;}

Page 34: Java Exceptions

Another Explicit throwAnother Explicit throw

class MyExceptionThrow {class MyExceptionThrow {

public String readLines(DataInputStream in)public String readLines(DataInputStream in)

throws FewLinesException, IOException {throws FewLinesException, IOException {

int length = 1024, n = 0;int length = 1024, n = 0;

String line;String line;

line=in.readline();line=in.readline();

while (line!= null) {while (line!= null) {

n++; line = in.readLine();n++; line = in.readLine();

}}

if (n < length) throw new FewLinesException(); if (n < length) throw new FewLinesException();

// // Throw user defined exception Throw user defined exception

else return "Enough lines read in!";else return "Enough lines read in!";

} }} }

Page 35: Java Exceptions

Define your own Define your own Exception typesException types Exception classes can have constructors, Exception classes can have constructors,

methods, polymorphic methods, etc…methods, polymorphic methods, etc…

class FewLinesException extends IOException {class FewLinesException extends IOException { public FewLinesException() { }public FewLinesException() { } public FewLinesException(String msg) {public FewLinesException(String msg) { super(msg);super(msg); }}}}

Page 36: Java Exceptions

Handling Checked Handling Checked ExceptionsExceptions If you invoke a method that lists If you invoke a method that lists

a checked exception in its a checked exception in its throws throws clause, you must either:clause, you must either:– Catch the exception and handle it.Catch the exception and handle it.– Declare the exception in your methods Declare the exception in your methods throws throws

clause and let the exception pass through your clause and let the exception pass through your method by doing nothingmethod by doing nothing

Page 37: Java Exceptions

Must deal with thrown Must deal with thrown exceptionsexceptionsimport java.net.*;import java.net.*;

class Except1 {class Except1 {

static URL imageURL;static URL imageURL;

public static URL getURL(String urlstr) {public static URL getURL(String urlstr) {

return new URL(urlstr);return new URL(urlstr);

}}

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

imageURL = getURL("haha");imageURL = getURL("haha");

}}

}}

URL.URL() URL.URL() declared to throw declared to throw MalformedURLExceptionMalformedURLException

Except1.java:7: Exception java.net.MalformedURLException must be Except1.java:7: Exception java.net.MalformedURLException must be caught, or it must be declared in the throws clause of this methodcaught, or it must be declared in the throws clause of this method

Page 38: Java Exceptions

RuntimeException andRuntimeException andNon- RuntimeExceptionNon- RuntimeException

Non-RuntimeExceptionNon-RuntimeException– must must be caught be caught – or declared in the or declared in the throws throws clause of clause of

any method that can throw them.any method that can throw them. Subclasses of Subclasses of RuntimeExceptioRuntimeException, n,

ErrorError– unchecked exceptions unchecked exceptions (not (not

required to explicitly catch)required to explicitly catch)

Page 39: Java Exceptions

Still ComplainStill Complain

import java.net.*;import java.net.*;

class Except1 {class Except1 {

static URL imageURL;static URL imageURL;

public static URL getURL(String urlstr)public static URL getURL(String urlstr)

throws MalformedURLException{throws MalformedURLException{

return new URL(urlstr);return new URL(urlstr);

}}

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

imageURL = getURL("haha");imageURL = getURL("haha");

}}

}}

Page 40: Java Exceptions

No compile complainNo compile complain

import java.net.*;import java.net.*;

class Except1 {class Except1 {

static URL imageURL;static URL imageURL;

public static URL getURL(String urlstr)public static URL getURL(String urlstr)

throws MalformedURLException{throws MalformedURLException{

return new URL(urlstr);return new URL(urlstr);

}}

public static void main(String[] args)public static void main(String[] args)

throws MalformedURLException{throws MalformedURLException{

imageURL = getURL("haha");imageURL = getURL("haha");

}}

}}

Run-time complainRun-time complain

Page 41: Java Exceptions

Inheritance and Inheritance and Exception HandlingException Handling It is good practice to define your It is good practice to define your

own exception types.own exception types. Inheritance can be used.Inheritance can be used. It is good practice to define your It is good practice to define your

own exception types.own exception types. Catch exception object of Catch exception object of

superclass type allows for superclass type allows for polymorphic processing of related polymorphic processing of related errorserrors

Page 42: Java Exceptions

Java Exceptions and Java Exceptions and InheritanceInheritance

Page 43: Java Exceptions

Java Exceptions and Java Exceptions and InheritanceInheritance