CS 209 Programming in Java #10 Exception Handling

Similar documents
Exception-Handling Overview

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring 2017

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Programming II (CS300)

6.Introducing Classes 9. Exceptions

Programming II (CS300)

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

ECE 122. Engineering Problem Solving with Java

Data Structures. 02 Exception Handling

Chapter 12 Exception Handling

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Fundamentals of Object Oriented Programming

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

CS 209 Spring, 2006 Lab 8: GUI Development Instructor: J.G. Neal

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Introduction to Software Design

Chapter 13 Exception Handling

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Chapter 11. Java By Abstraction Chapter 11. Outline What Are Exceptions?

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

Exception Handling. Chapter 9

CS 209 Programming in Java #13 Multimedia

CS 180 Final Exam Review 12/(11, 12)/08

Std 12 Lesson-10 Exception Handling in Java ( 1

Java Programming Lecture 6

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

2.6 Error, exception and event handling

What can go wrong in a Java program while running?

Object Oriented Programming Exception Handling

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP1008 Exceptions. Runtime Error

Chapter 11 Handling Exceptions and Events. Chapter Objectives

ITI Introduction to Computing II

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

EXCEPTION HANDLING. Summer 2018

SampleApp.java. Page 1

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

CS112 Lecture: Exceptions and Assertions

ITI Introduction to Computing II

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Final Examination Semester 3 / Year 2008

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

Window Interfaces Using Swing Objects

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Name Section. CS 21a Introduction to Computing I 1 st Semester Final Exam

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

CSCI 261 Computer Science II

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions - Example. Exceptions - Example

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

More on Exception Handling

More on Exception Handling

Window Interfaces Using Swing. Chapter 12

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. Exception Handling

First Name: AITI 2004: Exam 2 July 19, 2004

CS Programming I: Exceptions

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Object Oriented Programming

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Lecture 19 Programming Exceptions CSE11 Fall 2013

Exceptions and Error Handling

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

EXCEPTIONS. Java Programming

CS11 Java. Fall Lecture 4

Exceptions. CSC207 Winter 2017

Correctness and Robustness

CS 209 Spring, 2006 Lab 11: Files & Streams Instructor: J.G. Neal

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

National University. Faculty of Computer Since and Technology Object Oriented Programming

Window Interfaces Using Swing Objects

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

COSC Exception Handling. Yves Lespérance. Lecture Notes Week 10 Exception Handling

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

! Errors can be dealt with at place error occurs

Page 1 of 7. public class EmployeeAryAppletEx extends JApplet

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Exception Handling in C++

Instruction to students:

AP CS Unit 11: Graphics and Events

Transcription:

CS 209 Programming in Java #10 Exception Handling Textbook Chapter 15 Spring, 2006 Instructor: J.G. Neal 1 Topics What is an Exception? Exception Handling Fundamentals Errors and Exceptions The try-catch-finally Structure The try, catch, and finally Blocks Selected Methods in Class Throwable Example Program Throwing an Exception Another Example Program 2

Types of Errors There are three types of errors: Syntax error: A violation of the grammar rules that define legal code. These rules define the legal use of the programming language with respect to the identifiers, keywords, symbols, literals, and expressions used and their arrangement. Can you give examples? Detected when? Detected by what? Runtime error: An error situation that arises during program execution; an illegal operation is performed Can you give examples? Detected when? Detected by what? Logical error: The program produces incorrect output results Can you give examples? Detected when? Detected by what? 3 What is an exception? Why is exception handling important? An exception is: An indication that a problem occurred during program execution (runtime) An unexpected condition or error condition Exception handling is important Purpose: To support robust, fault-tolerant programs Objective: Separation of error handling code from the program code that implements the required objects and functionality 4

When can exceptions occur? Exceptions occur when a program tries to perform runtime operations such as: Divide by zero Pass invalid parameters to a method Use a null reference (pointer) to access a method in a class Convert data to an incompatible type among others... Can you list other examples? 5 Partial Java Class Hierarchy AWTError LinkageError Error ThreadDeath Object Throwable VirtualMachineError BadLocationException (java.swing.text) Exception DataFormatException (java.util.zip) IOException (java.io) SQLException (java.sql) RuntimeException 6

Error Error class: A subclass of the Throwable class Purpose: Indicate serious problems that a reasonable application should not try to catch Most such errors are abnormal conditions Example: Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class Note: ThreadDeath error: Though a "normal" condition, is also a subclass of Error because most applications should not try to catch it 7 Exception The Exception class and its subclasses: A type of Throwable that indicates conditions that a reasonable application might want to catch and handle Exception handling: Deal with synchronous errors that occur as the program executes certain instructions Examples: out-of-bounds array subscript, division by zero, null pointer, invalid method parameters, file not found, class cast problem, bad location in text document Not designed to deal with asynchronous events Examples: disk I/O completions, network message arrivals, user manipulation of GUI widgets Use event listeners for these 8

What can you do with exceptions? Program code can do the following: Catch and handle exceptions Throw exceptions Define new types of exceptions Define methods that throw exceptions 9 The try-catch-finally structure Purpose: to catch and handle exceptions try block: Encloses the code that may generate an exception catch block: Zero or more catch blocks immediately follow the try block Each specifies the type of exception it can catch Each contains an exception handler finally block: Optional Provides code that always executes regardless of whether or not an exception occurs If no catch blocks, then the finally block is required Commonly used to return resources to the system e.g., close any files opened in the try block 10

Syntax try { // statements; // resource-acquisition statements; } catch ( ExceptionType1 ex1 ) { // exception-handling statements; } catch ( ExceptionType2 ex2 ) { // exception-handling statements; } finally { // optional block if a catch block is present // statements; // resource-release statements; } 11 Example try { // Convert numbers from type String to type int int1 = Integer.parseInt( firstinteger ); int2 = Integer.parseInt( secondinteger ); } catch( NumberFormatException ex ) { // Display error message via JOptionPane String msg = Illegal input in text field\n + Please enter the number again ; JOptionPane.showMessageDialog( null, msg, Error Message, JOptionPane.PLAIN_MESSAGE); return; } 12

The try-catch-finally structure How it works When an exception is thrown, program control exits the try block and searches the catch blocks for an appropriate handler If the type of the thrown exception matches the parameter type in one of the catch blocks, the code for that catch block is executed If no exceptions are thrown, the catch blocks are skipped and program execution resumes after the last catch block If a finally block appears after the last catch block, it is executed regardless of whether or not an exception is thrown 13 Useful Methods in Class Throwable getmessage() object - Returns the error message string of this Throwable printstacktrace() - Prints this Throwable object and its backtrace to the standard error stream printstacktrace( PrintStream s ) - Prints this Throwable object and its backtrace to the specified print stream tostring() - Returns a short description of this Throwable object 14

Example Program Purpose: To demonstrate exceptions and The use of exception handling Program: Project: ExceptionsExs Package: exceptionexs File: NumberFormatEx.java Questions: See next slides (continued on next slide) 15 Example Program Questions: Where do you place a try-catch structure? What do you put in the try block? What do you put in the catch block? What are some action choices when catching and handling an exception? (continued on next slide) 16

Example Program Questions: Can the program get the erroneous characters entered (for display to user)? Does the program detect all error conditions and notify the user? What happens in the case of an exception that is not detected by our program? How can we change the program so that it can tell the user which text field contains the illegal input? Show the difference between using tostring() and getmessage() Demonstrate the use of multiple catch blocks Demonstrate that a finally block will always be executed 17 Example Program 18

Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\NumberFormatEx.java a 1 package 2 import 3 import 4 import 5 import 6 7 public class NumberFormatEx extends JFrame implements ActionListener { 8 // Instance variables 9 private // Present instructions to user 10 private // Prompts for user input 11 private // Mechanisms to get user input 12 13 private int int1, // First integer from user // Second integer from user 15 16 private int sum, // Sum of the two input integers 17 difference, // Difference of the two input integers 18 product, // Product of the two input integers 19 quotient, // Quotient of the two input integers // Remainder from the two input integers 21 22 private // Output display area 23 private int // Width of the JTextArea 24 private int // Height of the JTextArea 25 26 // The main method required for an application program 27 public static void main( String[] args ) { 28 JFrame frame = new NumberFormatEx // Construct the window 29 frame.setsize( new Dimension // Set its size 30 frame.setdefaultcloseoperation 31 frame.setvisible( true // Make the window visible 32 } 33 34 // Constructor 35 public NumberFormatEx() { 36 super 37 Container c = getcontentpane 38 c.setlayout( new BorderLayout 39 40 JPanel jpan = new JPanel(new GridLayout 42 jpan.setborder(new TitledBorder 43 44 prompt1 = new JLabel 45 jpan.add // put prompt on window 46 input1 = new JTextField 47 jpan.add // put input JTextField on window 48 Page 1

Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\NumberFormatEx.java a 49 prompt2 = new JLabel 50 jpan.add // put prompt on window 51 input2 = new JTextField 52 jpan.add // put input JTextField on window 53 54 c.add 55 56 // Create and display a text area for presenting results 57 TDisplay = new JTextArea( composedisplaystring(), 59 TDisplay.setLineWrap( true 60 TDisplay.setWrapStyleWord( true 61 c.add 62 63 // "this" window will respond to user input in text fields 64 input1.addactionlistener ( this 65 input2.addactionlistener ( this 66 } 67 68 // Process user's action in JTextField input 69 public void actionperformed ( ActionEvent e) { 70 // Get the string data from the JTextFields 71 String firstinteger = input1.gettext 72 String secondinteger = input2.gettext 73 74 try { // Convert numbers from type String to type int 75 int1 = Integer.parseInt 76 int2 = Integer.parseInt 77 } 78 catch( NumberFormatException ex ) { 79 // Display error message via JOptionPane 80 81 String msg = "Illegal input in text field\nplease enter the 82 JOptionPane.showMessageDialog( 83 null 84 } 85 86 // Perform arithmetic computations and display the results 87 performcomputations 88 TDisplay.setText(composeDisplayString 89 } 90 91 // Method to perform arithmetic computations 92 public void performcomputations() { Page 2

Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\NumberFormatEx.java a 98 } 99 100 // Method to compose the string for displaying computation results 101 public String composedisplaystring() { 102 return "First integer: " + int1 + "\nsecond integer: " + int2 + 103 "\n\nsum: " + sum + "\ndifference: " + difference + 104 "\nproduct: " + product + 106 } 107 } Page 3

Throwing an Exception A throws clause is needed in order for a method to throw an exception: returntype methodname(... ) throws ex1, ex2, ex3 { // Method body } The throw point: Place in method body at which throw is executed A throw statement is used to indicate when an exception has occurred (i.e., a method could not complete successfully) Errors and RuntimeExceptions can be thrown from almost any method and need not be listed in the throws clause These unlisted items are called unchecked All other exceptions that a method can throw must be listed in the method s throws clause These listed items are called checked 19 Example Program Purpose: To demonstrate How to define a new exception class (type) for a particular situation How to define a method that checks for certain error conditions (invalid entry of integer data) and throws the new exception type when error conditions occur Program: Project: ExceptionsExs Package: exceptionexs File: ExceptionDemo.java Questions: See next slide 20

Questions: Example Program Can the program detect which text field was the source of error? If so, how can the program report which text field it was? If the user does not enter anything in one of the text fields, an exception is thrown. How can the program intercept this and provide a better message to the user? (continued on next slide) 21 Exception Program Example 22

Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\ExceptionDemo.java at 1 // Purpose: Provide an example of a programmer-defined exception class, 2 // MyConvertException, and a programmer-defined method that 3 // throws an exception 4 package 5 import 6 import 7 import 8 import 9 10 public class ExceptionDemo extends JFrame implements ActionListener { 11 // Instance variables 12 private // Mechanisms to get user input 13 private int // The integers from user 14 15 private // Output display area 16 private int // Width of the JTextArea 17 private int // Height of the JTextArea 18 19 // The main method required for an application program 20 public static void main( String[] args ) { 21 JFrame frame = new ExceptionDemo // Construct the window 22 frame.setsize( new Dimension // Set its size 23 frame.setdefaultcloseoperation 24 frame.setvisible( true // Make the window visible 25 } 26 27 // Constructor 28 public ExceptionDemo () { 29 super 30 Container c = getcontentpane 31 c.setlayout( new BorderLayout 32 33 JPanel jpan = new JPanel 34 jpan.setborder(new EtchedBorder 35 Box box = Box.createVerticalBox 36 37 JLabel prompt1 = new JLabel("Enter two integers, then hit the Enter key:", 39 input1 = new JTextField 40 input2 = new JTextField 41 42 box.add 43 box.add 44 box.add 45 jpan.add 46 c.add 47 Page 1

Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\ExceptionDemo.java at 48 // Create and display a text area for presenting results 49 TDisplay = new JTextArea( composedisplaystring(), 51 TDisplay.setBorder(new EtchedBorder 52 TDisplay.setLineWrap( true 53 TDisplay.setWrapStyleWord( true 54 TDisplay.setEditable(false 55 c.add 56 57 // "this" window will respond to user input in text field 58 input1.addactionlistener ( this 59 input2.addactionlistener ( this 60 } 61 62 // Process user's action in JTextField 63 public void actionperformed ( ActionEvent e) { 64 // Get the string data from the JTextFields 65 String numbstr1 = input1.gettext 66 String numbstr2 = input2.gettext 67 68 try { // Convert input from type String to type int 69 int1 = converttointeger 70 int2 = converttointeger 71 } 72 catch( MyConvertException ex ) { 73 String msg = "Catch block parameter matches MyConvertException\n" + ex.tostring 74 JOptionPane.showMessageDialog( 75 null 76 return 77 } 78 catch ( Exception ex ) { 79 String msg = "Catch block parameter matches Exception\n" + ex. tostring 80 JOptionPane.showMessageDialog( 81 null 82 return 83 } 84 // Display the results 85 TDisplay.setText(composeDisplayString 86 input1.settext 87 input2.settext 88 } 89 90 exception 91 public int converttointeger( String str ) throws MyConvertException, MyEmptyStringException { Page 2

Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\ExceptionDemo.java at 92 int // Hold the integer version of converted char 93 char // Hold the character extracted from text field string 95 96 if (str.length() == 0) 97 throw new MyEmptyStringException 98 99 char sign = str.charat 100 if ( sign == '-' ) 101 tempstr = tempstr.substring 102 103 for ( int length 104 ch = tempstr.charat 105 if (!Character.isDigit(ch) ) { 106 throw new MyConvertException 107 } 108 } 109 return Integer.parseInt 110 } 111 112 // Method to compose the text for displaying results 113 public String composedisplaystring() { 114 return "First integer entered: " + int1 + 115 "\nsecond integer entered: " + int2 + 116 "\n\nsum = " + (int1+int2) + 118 } 119 } 120 121 // Purpose: Exception indicating that the input data is not valid 122 class MyConvertException extends Exception { 123 // Constructor 124 MyConvertException(int pos, char ch) { 125 super("the input contains invalid character " + ch + " at position 126 } 127 } 128 129 // Purpose: Exception indicating that the input data is not valid 130 class MyEmptyStringException extends Exception { 131 // Constructor 132 MyEmptyStringException() { 133 super 134 } 135 } Page 3