Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Yoshi
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
For use of Cleveland State's IST410 Students only 1 Exception.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Chapter 10 – Exception Handling
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Web Design & Development Lecture 7
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

Java Exceptions

Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: 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.

Traditional Ways An exception is an indication that something went wrong in a program. Traditionaly, error checking is tangled with the code that provides normal functionality. An exception is an indication that something went wrong in a program. Traditionaly, error checking is tangled with the code that provides normal functionality.…… if(num != 0) { result = 100/num; result = 100/num;}else{ //print error //print error //get new value //get new value //do more stuff //do more stuff}……

Java Exceptions The error checking and recovery breaks up the flow of normal processing. The error checking and recovery breaks up the flow of normal processing. Removing error checking and recovery from the normal flow of a program will: Removing error checking and recovery from the normal flow of a program will: –Make code easier to read –Make code easier to write Exception handling allows programmers to handle exceptional cases outside the normal flow of control. Exception handling allows programmers to handle exceptional cases outside the normal flow of control.

Addition Example We saw earlier that our Addition class did not catch possible exceptions. We saw earlier that our Addition class did not catch possible exceptions. –Invoking Integer.parseInt(String) resulted in a NumberFormatException if the string provided did not represent a valid integer.

Catching Exception (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...

Catching Exception (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; } …

Exception Hierarchy

Java Errors In Java the Error class defines serious errors that the programmer should not even attempt to recover from. Typical Errors are: –Virtual Machine Errors –Out of memory –Stack overflow –Windowing Error

Java Exceptions In Java the Exception class defines mild error conditions that your programs might encounter. In Java the Exception class defines mild error conditions that your programs might encounter. Rather than blindly terminating the program, you can write code to handle your exceptions and continue executing the program. Rather than blindly terminating the program, you can write code to handle your exceptions and continue executing the program. RunTimeException RunTimeException Other type of Exceptions (We call them Non RunTimeException) Other type of Exceptions (We call them Non RunTimeException)

Typical exceptions –The file you are trying to open doesn’t exist –The network connection is disrupted –The user entered invalid data –The numeric values you are manipulating are out of the prescribed range –Trying to use an uninitialized reference –Going outside the bounds of an array

try/catch try/catch blocks are used to catch and handle exceptions try{ … //normal flow of program } catch(Exceptiontype reference) { … //exception handler code }

try/catch If an exception occurs within a try block, all catch blocks will be searched for a matching exception type. If an exception occurs within a try block, all catch blocks will be searched for a matching exception type. The keyword throw is used to throw an exception The keyword throw is used to throw an exception throw new ExceptionType(); The exception can be thrown from within a method and be handled by the caller. The exception can be thrown from within a method and be handled by the caller.

try/catch Catch blocks specify different types (All derived from ‘Throwable’) of exceptions. Catch blocks specify different types (All derived from ‘Throwable’) of exceptions. If an exception is caught, the flow of control will enter the catch block. If an exception is caught, the flow of control will enter the catch block. Once the block is done executing, flow of control will pick up after the last catch block Once the block is done executing, flow of control will pick up after the last catch block

try/catch If an exception is not caught locally, the next enclosing try/catch block will be tested. If an exception is not caught locally, the next enclosing try/catch block will be tested. The order of enclosing try/catch blocks will follow the call stack. The order of enclosing try/catch blocks will follow the call stack.

finally The finally statement defines a block of code that always executes regardless of whether an exception was caught. try {//protected code startFaucet(); startFaucet(); waterLawn(); waterLawn();} catch(Exception e) { //handle exception //handle exception}finally{ stopFaucet(); stopFaucet();}

What need to be done for the three types of exceptions There are two types of exceptions in Java: There are two types of exceptions in Java: –RuntimeException- indicates a design or implementation problem that occurs because the programmer made a mistake. This should never happen if the program is running properly. Not required by compiler to be handled. Programmer is encouraged to handle though –Non-RuntimeException- indicates difficulty at runtime. File not present, user enters invalid data. must be checked, either handled or propagate

Common Exceptions –ArithmeticException –NullPointerException –NegativeArraySizeException –ArrayIndexOutOfBoundsException –SecurityException –IOException

Handle or Declare Rule Java requires that if an Non RunTimeException occurs while a method is executing the caller must determine what action is to be taken. Java requires that if an Non RunTimeException occurs while a method is executing the caller must determine what action is to be taken. There are two things that can be done by the caller There are two things that can be done by the caller –Enclose the method call in a try/catch block –Indicate that the calling method will not handle the exception

Handle or Declare Rule To indicate that the calling method will not handle the exception use the keyword throws in the method definition. To indicate that the calling method will not handle the exception use the keyword throws in the method definition. public void foo() throws ExceptionType This indicates that foo will not handle the exception, but whoever called foo will. This indicates that foo will not handle the exception, but whoever called foo will. This rule only applies for exceptions derived from Exception but not derived from RuntimeException This rule only applies for exceptions derived from Exception but not derived from RuntimeException

Try, Catch, Finally try tryblock tryblock catch (exception_type identifier) catchblock catchblock catch (exception_type identifier) catchblock catchblock // 0 or more of these finally // 0 or 1 of these finallyblock finallyblock

Try, Catch and Finally Execute tryblock of statements until either an exception is thrown or the block finishes successfully. Execute tryblock of statements until either an exception is thrown or the block finishes successfully. If an exception is thrown, the catch clauses are examined in order, to find one for an exception of the thrown class or one of the thrown classes superclasses. If an exception is thrown, the catch clauses are examined in order, to find one for an exception of the thrown class or one of the thrown classes superclasses. If none are found, propagate the exception to a surrounding try block, and if needed to the calling method. If none are found, propagate the exception to a surrounding try block, and if needed to the calling method. The finally block is always executed, even if no exceptions are thrown. The finally block is always executed, even if no exceptions are thrown.

Another try/catch example 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; }

Propagating an Exception if you call a method that throws a checked exception, you must either handle it or propagate it. if you call a method that throws a checked exception, you must either handle it or propagate it. propagate an Exception by adding a throw clause in the method header propagate an Exception by adding a throw clause in the method header

Example 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; }

Finally Example 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 found return true; //word found return false; //word not found return false; //word not found } finally { // finally block is executed whether or not try throws an exception. // finally block is executed whether or not try throws an exception. if (input != null) if (input != null) input.close(); }} input.close(); }}

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

main() { fie(); fie();} fie() { 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.

Throwing Exception Exceptions are thrown (signaled) when Exceptions are thrown (signaled) when –you make a programming error (system throws an exception implicitly.) –you call a method that throws an exception. –you detect an error and throw an exception explicitly. – an internal error occurs in Java. (Error Class)

Example 1 class ImplicitThrow { 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 ArithmeticException Unchecked exceptions need not be declared

Example 2 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 MalformedURLException, IOException Throws MalformedURLException, IOException Method Must declare checked exceptions Method Must declare checked exceptions

Explicitly Throw an Exception Find an appropriate exception class from the API (or define your own by subclassing Exception ) Find an appropriate exception class from the API (or define your own by subclassing Exception ) create an object of that class create an object of that class throw it throw it Thrown exceptions dealt with by calling method. This declaration forces calling method to catch exception or propagate it. Thrown exceptions dealt with by calling method. This declaration forces calling method to catch exception or propagate it. Rethrow? Rethrow?

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

Another Explicit throw 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!"; } } } }

Define your own Exception types Exception classes can have constructors, methods, polymorphic methods, etc… Exception classes can have constructors, methods, polymorphic methods, etc… class FewLinesException extends IOException { public FewLinesException() { } public FewLinesException() { } public FewLinesException(String msg) { public FewLinesException(String msg) { super(msg); super(msg); }}

Handling Checked Exceptions If you invoke a method that lists a checked exception in its throws clause, you must either: If you invoke a method that lists a checked exception in its throws clause, you must either: –Catch the exception and handle it. –Declare the exception in your methods throws clause and let the exception pass through your method by doing nothing

Must deal with thrown exceptions import java.net.*; 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() declared to throw MalformedURLException Except1.java:7: Exception java.net.MalformedURLException must be caught, or it must be declared in the throws clause of this method

RuntimeException and Non- RuntimeException Non-RuntimeException Non-RuntimeException –must be caught –or declared in the throws clause of any method that can throw them. Subclasses of RuntimeExceptio n, Error Subclasses of RuntimeExceptio n, Error –unchecked exceptions (not required to explicitly catch)

Still Complain import java.net.*; 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"); }}

No compile complain import java.net.*; 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 complain

Inheritance and Exception Handling It is good practice to define your own exception types. It is good practice to define your own exception types. Inheritance can be used. Inheritance can be used. It is good practice to define your own exception types. It is good practice to define your own exception types. Catch exception object of superclass type allows for polymorphic processing of related errors Catch exception object of superclass type allows for polymorphic processing of related errors

Java Exceptions and Inheritance