CS 209 Programming in Java #10 Exception Handling
|
|
- Kerry Morrison
- 6 years ago
- Views:
Transcription
1 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
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
3 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
4 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
5 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
6 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
7 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
8 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
9 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
10 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 private int int1, // First integer from user // Second integer from user 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 private // Output display area 23 private int // Width of the JTextArea 24 private int // Height of the JTextArea // 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 } // Constructor 35 public NumberFormatEx() { 36 super 37 Container c = getcontentpane 38 c.setlayout( new BorderLayout JPanel jpan = new JPanel(new GridLayout 42 jpan.setborder(new TitledBorder 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
11 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 c.add // 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 // "this" window will respond to user input in text fields 64 input1.addactionlistener ( this 65 input2.addactionlistener ( this 66 } // 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 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 String msg = "Illegal input in text field\nplease enter the 82 JOptionPane.showMessageDialog( 83 null 84 } // Perform arithmetic computations and display the results 87 performcomputations 88 TDisplay.setText(composeDisplayString 89 } // Method to perform arithmetic computations 92 public void performcomputations() { Page 2
12 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\Exceptions\ExceptionExs\src\exceptionexs\NumberFormatEx.java a 98 } // Method to compose the string for displaying computation results 101 public String composedisplaystring() { 102 return "First integer: " + int1 + "\nsecond integer: " + int "\n\nsum: " + sum + "\ndifference: " + difference "\nproduct: " + product } 107 } Page 3
13 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
14 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
15 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 private // Output display area 16 private int // Width of the JTextArea 17 private int // Height of the JTextArea // 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 } // Constructor 28 public ExceptionDemo () { 29 super 30 Container c = getcontentpane 31 c.setlayout( new BorderLayout JPanel jpan = new JPanel 34 jpan.setborder(new EtchedBorder 35 Box box = Box.createVerticalBox JLabel prompt1 = new JLabel("Enter two integers, then hit the Enter key:", 39 input1 = new JTextField 40 input2 = new JTextField box.add 43 box.add 44 box.add 45 jpan.add 46 c.add 47 Page 1
16 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 // "this" window will respond to user input in text field 58 input1.addactionlistener ( this 59 input2.addactionlistener ( this 60 } // 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 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 } exception 91 public int converttointeger( String str ) throws MyConvertException, MyEmptyStringException { Page 2
17 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 if (str.length() == 0) 97 throw new MyEmptyStringException char sign = str.charat 100 if ( sign == '-' ) 101 tempstr = tempstr.substring for ( int length 104 ch = tempstr.charat 105 if (!Character.isDigit(ch) ) { 106 throw new MyConvertException 107 } 108 } 109 return Integer.parseInt 110 } // Method to compose the text for displaying results 113 public String composedisplaystring() { 114 return "First integer entered: " + int "\nsecond integer entered: " + int "\n\nsum = " + (int1+int2) } 119 } // 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 } // 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
Exception-Handling Overview
م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the
More informationBBM 102 Introduction to Programming II Spring Exceptions
BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom
More informationBBM 102 Introduction to Programming II Spring 2017
BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception
More informationCOMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed
1 1 COMP200 EXCEPTIONS OOP using Java, based on slides by Shayan Javed Exception Handling 2 3 Errors Syntax Errors Logic Errors Runtime Errors 4 Syntax Errors Arise because language rules weren t followed.
More informationCS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling
CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and
More information6.Introducing Classes 9. Exceptions
6.Introducing Classes 9. Exceptions Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions
More informationLe 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
Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java
More informationCSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige
CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions Overview Problem: Can we detect run-time errors and take corrective action? Try-catch Test for a variety of different program situations
More informationData Structures. 02 Exception Handling
David Drohan Data Structures 02 Exception Handling JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.
More informationChapter 12 Exception Handling
Chapter 12 Exception Handling 1 Motivations Goal: Robust code. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can
More informationException Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11
Outline Chapter 11 Exception Handling 11.1 What are Exceptions? 11.1.1 Exception Handling 11.1.2 The Delegation Model 11.2 Java's Exception Constructs 11.2.1 The Basic -catch Construct 11.2.2 Handling
More informationCSC207H: Software Design. Exceptions. CSC207 Winter 2018
Exceptions CSC207 Winter 2018 1 What are exceptions? Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-tothe-next-step,
More informationFundamentals of Object Oriented Programming
INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of
More informationChapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Chapter 8 Exception Handling CS 180 Sunil Prabhakar Department of Computer Science Purdue University Clarifications Auto cast from char to String does not happen. Cast between int and char happens automatically.
More informationCS 209 Spring, 2006 Lab 8: GUI Development Instructor: J.G. Neal
CS 209 Spring, 2006 Lab 8: GUI Development Instructor: J.G. Neal Objectives: To gain experience with the programming of: 1. Graphical user interfaces (GUIs), 2. GUI components, and 3. Event handling (required
More informationException Handling in Java. An Exception is a compile time / runtime error that breaks off the
Description Exception Handling in Java An Exception is a compile time / runtime error that breaks off the program s execution flow. These exceptions are accompanied with a system generated error message.
More informationObject oriented programming. Instructor: Masoud Asghari Web page: Ch: 7
Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential
More informationReminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling
Reminder CSE 1720 Lecture 11 Exception Handling Midterm Exam" Thursday, Feb 16, 10-11:30" CLH J Curtis Lecture Hall, Room J! will cover all material up to and including Tues Feb 14th! Tues, Feb 7 topic:
More informationLecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166
Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions
More informationIntroduction to Software Design
CSI 1102 1 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments
More informationChapter 13 Exception Handling
Chapter 13 Exception Handling 1 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or
More informationIntroduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1
Exceptions: An OO Way for Handling Errors Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such
More informationCSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1
CSCI 6234 Object Oriented Design: Java Review Errors George Blankenship Java Review - Errors George Blankenship 1 Errors Exceptions Debugging Java Review Topics Java Review - Errors George Blankenship
More informationCSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship
CSCI 6234 Object Oriented Design: Java Review Errors George Blankenship George Blankenship 1 Errors Exceptions Debugging Java Review Topics George Blankenship 2 Program Errors Types of errors Compile-time
More informationException Handling. Sometimes when the computer tries to execute a statement something goes wrong:
Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer
More informationExceptions, try - catch - finally, throws keyword. JAVA Standard Edition
Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception
More informationException Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:
Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes
More informationException Handling. Chapter 11. Java By Abstraction Chapter 11. Outline What Are Exceptions?
Chapter 11 Exception Handling Java By Abstraction 11-1 Outline 11.1 What are Exceptions? 11.1.1 Exception Handling 11.1.2 The Delegation Model 11.2 Java's Exception Constructs 11.2.1 The Basic -catch Construct
More informationA problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions
A problem?... Exceptions Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions 2 A problem?... A problem?... 3 4 A problem?... A problem?... 5 6 A problem?...
More informationException Handling. Chapter 9
Exception Handling Chapter 9 Objectives Describe the notion of exception handling React correctly when certain exceptions occur Use Java's exception-handling facilities effectively in classes and programs
More informationCS 209 Programming in Java #13 Multimedia
CS 209 Programming in Java #13 Multimedia Part of Textbook Chapter 14 Spring, 2006 Instructor: J.G. Neal 1 Topics Multimedia Displaying Images Using the MediaTracker class Images in Applets and Applications
More informationCS 180 Final Exam Review 12/(11, 12)/08
CS 180 Final Exam Review 12/(11, 12)/08 Announcements Final Exam Thursday, 18 th December, 10:20 am 12:20 pm in PHYS 112 Format 30 multiple choice questions 5 programming questions More stress on topics
More informationStd 12 Lesson-10 Exception Handling in Java ( 1
Ch-10 : Exception Handling in Java 1) It is usually understood that a compiled program is error free and will always successfully. (a) complete (b) execute (c) perform (d) accomplish 2) In few cases a
More informationJava Programming Lecture 6
Java Programming Lecture 6 Alice E. Fischer Feb 15, 2013 Java Programming - L6... 1/32 Dialog Boxes Class Derivation The First Swing Programs: Snow and Moving The Second Swing Program: Smile Swing Components
More informationCS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun
CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun Announcements You ve started (or finished) project 1, right? Package Visibility public declarations represent specifications what
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More information2.6 Error, exception and event handling
2.6 Error, exception and event handling There are conditions that have to be fulfilled by a program that sometimes are not fulfilled, which causes a so-called program error. When an error occurs usually
More informationWhat can go wrong in a Java program while running?
Exception Handling See https://docs.oracle.com/javase/tutorial/ essential/exceptions/runtime.html See also other resources available on the module webpage This lecture Summary on polymorphism, multiple
More informationObject Oriented Programming Exception Handling
Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of
More informationCS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions
CS112 Lecture: Exceptions Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions Materials: 1. Online Java documentation to project 2. ExceptionDemo.java to
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception
More informationCOMP1008 Exceptions. Runtime Error
Runtime Error COMP1008 Exceptions Unexpected error that terminates a program. Undesirable Not detectable by compiler. Caused by: Errors in the program logic. Unexpected failure of services E.g., file server
More informationChapter 11 Handling Exceptions and Events. Chapter Objectives
Chapter 11 Handling Exceptions and Events Chapter Objectives Learn what an exception is See how a try/catch block is used to handle exceptions Become aware of the hierarchy of exception classes Learn about
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More informationDay 8. COMP1006/1406 Summer M. Jason Hinek Carleton University
Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there
More informationEXCEPTION HANDLING. Summer 2018
EXCEPTION HANDLING Summer 2018 EXCEPTIONS An exception is an object that represents an error or exceptional event that has occurred. These events are usually errors that occur because the run-time environment
More informationSampleApp.java. Page 1
SampleApp.java 1 package msoe.se2030.sequence; 2 3 /** 4 * This app creates a UI and processes data 5 * @author hornick 6 */ 7 public class SampleApp { 8 private UserInterface ui; // the UI for this program
More informationJava. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java
Computer Science Error, Exception, and Event Handling Java 02/23/2010 CPSC 449 228 Unless otherwise noted, all artwork and illustrations by either Rob Kremer or Jörg Denzinger (course instructors) Error,
More informationCS112 Lecture: Exceptions and Assertions
Objectives: CS112 Lecture: Exceptions and Assertions 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions 3. Introduce assertions Materials: 1. Online Java documentation
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More informationLecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:
Lecture 28 Exceptions and Inner Classes Goals We are going to talk in more detail about two advanced Java features: Exceptions supply Java s error handling mechanism. Inner classes ease the overhead of
More informationFinal Examination Semester 3 / Year 2008
Southern College Kolej Selatan 南方学院 Final Examination Semester 3 / Year 2008 COURSE : JAVA PROGRAMMING COURSE CODE : PROG1114 TIME : 2 1/2 HOURS DEPARTMENT : COMPUTER SCIENCE CLASS : CS08-A + CS08-B LECTURER
More informationException Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES
1 2 13 Exception Handling It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. Franklin Delano Roosevelt O throw away the worser
More informationIntroduction This assignment will ask that you write a simple graphical user interface (GUI).
Computing and Information Systems/Creative Computing University of London International Programmes 2910220: Graphical Object-Oriented and Internet programming in Java Coursework one 2011-12 Introduction
More informationExceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions
Errors and Exceptions 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 An exception is a problem whose cause is outside
More informationIntroduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.
Introduction to Computation and Problem Solving Class 25: Error Handling in Java Prof. Steven R. Lerman and Dr. V. Judson Harward Goals In this session we are going to explore better and worse ways to
More informationWindow Interfaces Using Swing Objects
Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs
More informationExceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages
References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/
More informationName Section. CS 21a Introduction to Computing I 1 st Semester Final Exam
CS a Introduction to Computing I st Semester 00-00 Final Exam Write your name on each sheet. I. Multiple Choice. Encircle the letter of the best answer. ( points each) Answer questions and based on the
More informationCS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1
P a g e 1 CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1 Q1 Describe some Characteristics/Advantages of Java Language? (P#12, 13, 14) 1. Java
More informationCSCI 261 Computer Science II
CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -
More informationExceptions. CSE 142, Summer 2002 Computer Programming 1.
Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»
More informationExceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.
Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented
More informationExceptions - Example. Exceptions - Example
- Example //precondition: x >= 0 public void sqrt(double x) double root; if (x < 0.0) //What to do? else //compute the square root of x return root; 1 - Example //precondition: x >= 0 public void sqrt(double
More informationExceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar
Exceptions Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie
More informationMore on Exception Handling
Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationMore on Exception Handling
Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationWindow Interfaces Using Swing. Chapter 12
Window Interfaces Using Swing 1 Reminders Project 7 due Nov 17 @ 10:30 pm Project 6 grades released: regrades due by next Friday (11-18-2005) at midnight 2 GUIs - Graphical User Interfaces Windowing systems
More informationSome examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. Exception Handling
Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani Exception Handling There are three sources that can lead to exceptions: The End User Garbage-in, garbage-out
More informationFirst Name: AITI 2004: Exam 2 July 19, 2004
First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: JSP Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand
More informationCS Programming I: Exceptions
CS 200 - Programming I: Marc Renault Department of Computer Sciences University of Wisconsin Madison Spring 2018 TopHat Sec 3 (AM) Join Code: 427811 TopHat Sec 4 (PM) Join Code: 165455 Command-Line Arguments
More informationChapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited
Chapter 12 Exception Handling and Text IO Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations When a program runs into a runtime error,
More informationObject Oriented Programming
Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch
More informationEXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories
Objectives Define exceptions 8 EXCEPTIONS Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions 271 272 Exceptions
More informationOBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616
OBJECT ORIENTED PROGRAMMING Course 6 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Exceptions An event, which occurs during the execution of a program, that disrupts the normal flow of the program's
More informationLecture 19 Programming Exceptions CSE11 Fall 2013
Lecture 19 Programming Exceptions CSE11 Fall 2013 When Things go Wrong We've seen a number of run time errors Array Index out of Bounds e.g., Exception in thread "main" java.lang.arrayindexoutofboundsexception:
More informationExceptions and Error Handling
Exceptions and Error Handling Michael Brockway January 16, 2015 Some causes of failures Incorrect implementation does not meet the specification. Inappropriate object request invalid index. Inconsistent
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions
COMP 213 Advanced Object-oriented Programming Lecture 17 Exceptions Errors Writing programs is not trivial. Most (large) programs that are written contain errors: in some way, the program doesn t do what
More informationEXCEPTIONS. Java Programming
8 EXCEPTIONS 271 Objectives Define exceptions Exceptions 8 Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions
More informationCS11 Java. Fall Lecture 4
CS11 Java Fall 2014-2015 Lecture 4 Java File Objects! Java represents files with java.io.file class " Can represent either absolute or relative paths! Absolute paths start at the root directory of the
More informationExceptions. CSC207 Winter 2017
Exceptions CSC207 Winter 2017 What are exceptions? In Java, an exception is an object. Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment:
More informationCorrectness and Robustness
Correctness and Robustness 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda Introduction
More informationCS 209 Spring, 2006 Lab 11: Files & Streams Instructor: J.G. Neal
CS 209 Spring, 2006 Lab 11: Files & Streams Instructor: J.G. Neal Objectives: To gain experience with basic file input/output programming. Note: 1. This lab exercise corresponds to Chapter 16 of the textbook.
More informationThe University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003
The University of Melbourne Department of Computer Science and Software Engineering 433-254 Software Design Semester 2, 2003 Answers for Tutorial 7 Week 8 1. What are exceptions and how are they handled
More informationNational University. Faculty of Computer Since and Technology Object Oriented Programming
National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java Exceptions in Java What is an exception? An exception is an error condition that changes
More informationWindow Interfaces Using Swing Objects
Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs
More informationTopic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations
Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write
More informationPIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017
PIC 20A Exceptions Ernest Ryu UCLA Mathematics Last edited: November 27, 2017 Introductory example Imagine trying to read from a file. import java.io.*; public class Test { public static void main ( String
More informationCOSC Exception Handling. Yves Lespérance. Lecture Notes Week 10 Exception Handling
COSC 1020 Yves Lespérance Lecture Notes Week 10 Exception Handling Recommended Readings: Horstmann: Ch. 14 Lewis & Loftus: Ch. 8 Sec. 0 Exception Handling Exception handling is a mechanism for making programs
More informationAbout This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions
Exceptions Revised 24-Jan-05 CMPUT 115 - Lecture 4 Department of Computing Science University of Alberta About This Lecture In this lecture we will learn how to use Java Exceptions to handle unusual program
More information! Errors can be dealt with at place error occurs
UCLA Stat 1D Statistical Computing and Visualization in C++ Instructor: Ivo Dinov, Asst. Prof. in Statistics / Neurology University of California, Los Angeles, Winter 200 http://www.stat.ucla.edu/~dinov/courses_students.html
More informationPage 1 of 7. public class EmployeeAryAppletEx extends JApplet
CS 209 Spring, 2006 Lab 9: Applets Instructor: J.G. Neal Objectives: To gain experience with: 1. Programming Java applets and the HTML page within which an applet is embedded. 2. The passing of parameters
More informationAdministration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11
Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday
More informationJava for Programmers Course (equivalent to SL 275) 36 Contact Hours
Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Course Overview This course teaches programmers the skills necessary to create Java programming system applications and satisfies the
More informationException Handling in C++
Exception Handling in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by
More informationInstruction to students:
Benha University 2 nd Term (2012) Final Exam Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 20/5/2012 Time: 3 hours Examiner: Dr. Essam Halim Instruction
More informationAP CS Unit 11: Graphics and Events
AP CS Unit 11: Graphics and Events This packet shows how to create programs with a graphical interface in a way that is consistent with the approach used in the Elevens program. Copy the following two
More information