TCU CoSc 10403 Programming with Java Handling Exceptions.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
 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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
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.
Preventing and Correcting Errors
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Object Oriented Programming
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
Slides Credit Umair Javed LUMS Web Application Development.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
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 Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
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.
Chapter 8-Exception Handling/ Robust Programming.
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 Handling How to handle the runtime errors.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
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.
CSE 1201 Object Oriented Programming
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Exception Handling Chapter 9.
Chapter 12 Exception Handling
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Abdulmotaleb El Saddik University of Ottawa
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
Exceptions 10-May-19.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

TCU CoSc Programming with Java Handling Exceptions

What is an Exception Imagine the following code that might appear in some Applet: int age = Integer.parseInt(ageTF.getText().trim()); Obviously, we are expecting a number will appear in the TextField and that it constitutes a legal integer age. Consider, however, the following possibilities: 1. What if the user types a “$” instead of a 4 by mistake? 2. What if the user enters a decimal point number rather than an integer? 3. What if the user holds down the “3” key too long and an extremely long number is accidentally entered? We don’t expect circumstances such as these -- but they do happen! Software must be designed to expect the unexpected!!!

What is an Exception Some things that can go wrong during the execution of a program (such as on the earlier slide) can’t be detected at compile-time — because the user has not yet made the mistake by entering the wrong data!! Another example: your program may attempt to divide one number by zero (ex. examSum/numberOfStudents ) Or your program may require that an integer value be entered into a TextField, and the user of the program enters a float value or some other illegal character. From the compiler’s point of view, there is nothing wrong with these statements, and problems will arise only when the program is actually executing. At that point an internal alarm goes off, and Java attempts to “throw an exception” signifying that something untoward has occurred.

Example import java.awt.*; import java.applet.*; public class TrivialApplet extends Applet { // // Deliberately divides by zero // to produce an exception. // public void init() { int numerator = 10; int denominator = 0; System.out.println ("This text will be printed."); System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); // because exception // occurs prior to // execution of this // statement } Note also: There is no code to handle the exception, if it occurs!

What is an Exception The system then immediately halts its normal mode of execution and goes off looking for help. With luck, the system will find some code in your program that will catch the exception and deal with it. Once caught, the alarm is silenced and the system picks up execution at a location after the block that contained the offending statement. Jargon: Java has its own terminology for exceptions. Exceptions are indicted by being thrown, and are detected elsewhere by being caught.

Terminology of Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled by another part of the program A program can be separated into a normal execution flow and an exception execution flow An error is also represented as an object in Java, but usually represents an unrecoverable situation and should not be caught

Some Possible Exceptions ArithmeticException - something, such as division by zero, has gone wrong in an arithmetic expression NumberFormatException -indicates that an illegal number format is being used. StringIndexOutOfBoundsException -an attempt has been made to use an inappropriate String index. NullPointerException -a class method is being called by an object instance that is currently null. EOFException-an end-of-file mark has been seen. IllegalArgumentException-a method has been called with an invalid argument. IndexOutOfBoundsException-an index into an array is out of bounds.

Exceptions As indicated on the earlier slide, Java has a predefined set of exceptions and errors that can occur during execution A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it in another place in the program The manner in which an exception is processed is an important design consideration

Exceptions If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message. The message includes a call stack trace that indicates the line on which the exception occurred. The call stack trace also shows the method call trail that lead to the attempted execution of the offending line. Remember, an exception is an object. The getMessage method returns a string explaining why the exception was thrown The printStackTrace method prints the call stack trace

The try Statement To process an exception when it occurs, the line that throws the exception is executed within a try block A try block is followed by one or more catch clauses, which contain code to process an exception Each catch clause has an associated exception type and is called an exception handler When an exception occurs, processing continues at the first catch clause that matches the “exception type”

Explanation of try block Java is instructed to try to execute a block of statements. If the statements in the block execute without producing an exception, the catch block is ignored, and execution continues beneath the catch block. However, if an exception is produced, we can specify that the catch block is to execute by stating the class of exception that we wish to catch. Basic form of try-catch block - try {... //a series of statements to be executed } catch (someException e) {... // code to handle the exception }

Exceptions import java.awt.*; import java.applet.*; public class TrivialApplet extends Applet { // // Deliberately divides by // zero to produce an exception. // public void init() { int numerator = 10; int denominator = 0; System.out.println ("This text will be printed."); try { System.out.println (numerator / denominator); } catch (ArithmeticException e) { System.out.println ("This text will now be printed."); }

Another Example import java.awt.*; import java.applet.*; import java.awt.event.*; public class ExceptionDemo1 extends Applet implements ActionListener { TextField stringField = new TextField(20), resultField = new TextField(20); Label resultLabel = new Label ("Answer:"), stringLabel = new Label("Type an integer:"); float number; public void init() { resultField.setEditable(false); add(stringLabel); add(stringField); stringField.addActionListener(this); add(resultLabel); add(resultField); } public void actionPerformed(ActionEvent event) { try { number = Float.parseFloat(stringField.getText().trim()); resultField.setText("Doubled value = " + (2 * number)); } catch (NumberFormatException e) { resultField.setText("Error in number - retype"); }

Exceptions As mentioned earlier, when a try block produces an exception, its execution is terminated - it is abandoned. A consequence of this is that any variables declared within the try block become inaccessible and cannot be used in the catch block, even if the catch block is in the same method. This can be a problem if we want to use those variables to produce a specific error message detailing what caused the problem. For example, you might want to display a wrongly formatted string if it was not able to be converted to an integer. A simple solution - any variable that is required inside the catch block must be declared outside the try block.

Examples try { String s = tf.getText().trim(); int x = Integer.parseInt(s); } catch (NumberFormatException e) {... // String s and int x not available here } String s = tf.getText().trim(); int x = 0; //initialized to 0 because of Java’s annoying warning message try { x = Integer.parseInt(s); } catch (NumberFormatException e) { // string s is available here since declared outside try System.out.println(s + “ input: “ + e.toString()); } System.out.println("Number = " + x); Note: 1500 entered into tf produces: Number = produces: “ 1.5 input: java.lang.NumberFormatException: For input string: "1.5” Number = 0 //produced by System.out.println() that appears after the catch xyz produces: “ xyz input: java.lang.NumberFormatException: For input string: "xyz” Number = 0 //produced by System.out.println() that appears after the catch

The search for a Catcher What if the program doesn’t catch a thrown exception? Actually, the rules for this depend on the class of exception. The basic principle is based on the fact that all programs, for the most part, are made up of methods. Thus, at run-time, an initial method is invoked, which itself invokes other methods, which in turn invoke others, etc… Imagine that methodA() invokes methodB() which invokes methodC(). If an exception occurs in methodC(), the search for an appropriate catch begins in methodC(). If one is not found, the search moves to methodB(), and then to methodA(), etc. If the top-level method does not provide a catch, an exception message is displayed and the program terminates abnormally (for an applet, it will continue to run and its results will be unreliable).

Still Another Example import java.awt.*; import java.applet.*; import java.awt.event.*; public class AnotherExceptionExample extends Applet implements ActionListener { TextField numField = new TextField(15), denomField = new TextField(15), resultField = new TextField(15); Label resultLabel = new Label ("Answer:"), denomLabel = new Label("Enter the denominator"), numLabel = new Label("Enter the numerator"); public void init() { add(numLabel); add(numField); numField.addActionListener(this); add(denomLabel); add(denomField); denomField.addActionListener(this); add(resultLabel); add(resultField); resultField.setEditable(false); } public void actionPerformed(ActionEvent event) { try { int numerator = Integer.parseInt(numField.getText().trim()); int denominator = Integer.parseInt(denomField.getText().trim()); resultField.setText("" + numerator/denominator); } catch (NumberFormatException e1) { resultField.setText("Error in number - "); } catch (ArithmeticException e2) { resultField.setText("Divide by Zero"); } //continue here afterwards }

Finally, finally The finally clause is used for activities that should be performed whether or not an exception was thrown and caught. Syntax: finally { //cleanup code } A try block can have at most one finally clause, and it must appear immediately after the last catch clause. The block of a finally clause is guaranteed to be executed, no matter how controls leaves its try block. If none of the catch clauses is executed, the finally clause is executed after the try block. If one of the catch clauses is executed, the finally clause is executed after completion of the catch. The finally clause is executed even if the try or catch portions contain break or return statements. A finally clause is generally used for cleanup purposes. (For example, emptying out TextFields to get ready for the next user input.