CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO
|
|
- Florence Harrell
- 6 years ago
- Views:
Transcription
1 CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO rights reserved. 2
2 Motivation 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 terminate gracefully? This is the subject we will introduce in this chapter rights reserved. 3 Objectives To get an overview of exceptions and exception handling ( 12.2). To explore the advantages of using exception handling ( 12.2). To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked vs. unchecked ( 12.3). To declare exceptions in a method header ( ). To throw exceptions in a method ( ). To write a try-catch block to handle exceptions ( ). To explain how an exception is propagated ( ). To obtain information from an exception object ( ). To develop applications with exception handling ( ). To use the finally clause in a try-catch block ( 12.5). To use exceptions only for unexpected errors ( 12.6). To rethrow exceptions in a catch block ( 12.7). To create chained exceptions ( 12.8). To define custom exception classes ( 12.9). To discover file/directory properties, to delete and rename files/directories, and to create directories using the File class ( 12.10). To write data to a file using the PrintWriter class ( ). To use try-with-resources to ensure that the resources are closed automatically ( ). To read data from a file using the Scanner class ( ). To understand how data is read using a Scanner ( ). To develop a program that replaces text in a file ( ). To read data from the Web ( 12.12). To develop a Web crawler ( 12.13). 4 rights reserved.
3 Exception Handling Exception handling enables a program to deal with exceptional situations and continue its normal execution No exception handling With if-else With a method With try-catch Quotient QuotientWithIf QuotientWithMethod QuotientWithException The benefit of using try-catch is that it enables a method to throw an exception to its caller method. Without this capability, a method must handle the exception itself or terminate the program rights reserved. 5 InputMismatchException Another way to handle similar exceptions is with the help of the InputMismatchException class Example: When executing input.nextint(), an InputMismatchException occurs if the input entered is not an int and the control is transferred to the catch block The statements in the catch block are now executed InputMismatchExceptionDemo rights reserved. 6
4 Exception Types Exceptions are objects based on the superclass java.lang.throwable ClassNotFoundException IOException ArithmeticException Exception NullPointerException timeexception IndexOutOfBoundsException Object Throwable Many more classes IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Many more classes rights reserved. 7 Checked & Unchecked Exceptions Throwable Exception Error All other exceptions timeexception subclasses subclasses subclasses Checked Exceptions Unchecked Exceptions 8
5 Errors caused by your program and external circumstances Throwable These rare internal system errors are thrown by JVM. If one occurs, notify the user and terminate the program Exception Error All other exceptions timeexception Caused by coding faults like bad casting, out-ofbounds array, etc. subclasses subclasses subclasses Checked Exceptions Unchecked Exceptions Program does not compile They happen only after the if any of these are present programs starts running 9 Handling Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example: o o A NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it An IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array These logic errors should be corrected in the program Unchecked exceptions can occur anywhere in the program To avoid cumbersome overuse of try-catch, Java does not mandate you to write code to catch unchecked exceptions rights reserved. 10
6 Declaring, Throwing and Catching Java s exception-handling model is based on three operations: 1. Declaring an exception 2. Throwing an exception 3. Catching an exception Exceptions are declared in and thrown from a method. The caller of that method can catch and handle the exception catch exception method1() { invoke method2; catch (Exception ex) { Process exception; method2() throws Exception { if (an error occurs) { throw new Exception(); declare exception throw exception rights reserved. 11 Declaring Exceptions Every method must state the types of checked exceptions it might throw This is known as declaring exceptions Examples: public void mymethod() throws IOException public void mymethod() throws IOException, OtherException rights reserved. 12
7 Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it This is known as throwing an exception Examples: throw new TheException(); TheException ex = new TheException(); throw ex; rights reserved. 13 Example: Throwing Exception /** Set a new radius */ public void setradius(double newradius) throws IllegalArgumentException { if (newradius >= 0) radius = newradius; else throw new IllegalArgumentException( "Radius cannot be negative"); rights reserved. 14
8 Catching Exceptions When an exception is thrown, it can be caught and handled in a try-catch block. If no exceptions arise during the execution of the try block, the catch blocks are skipped statements; // Statements that may throw exceptions catch (Exception1 exvar1) { // handler for exception1 catch (Exception2 exvar2) { // handler for exception2... catch (ExceptionN exvarn) { // handler for exceptionn If an exception is not caught in the current method, it is passed to the calling method. The process is repeated until the exception is caught or passed to main() 15 rights reserved. main method { invoke method1; statement1; catch (Exception1 ex1) { Process ex1; statement2; Call Stack Example: Catching Exceptions method1 { invoke method2; statement3; catch (Exception2 ex2) { Process ex2; statement4; method2 { invoke method3; statement5; catch (Exception3 ex3) { Process ex3; statement6; An exception is thrown in method3 1. If the exception type is Exception3, it is caught by the catch block for ex3 in method2. statement5 is skipped, and statement6 is executed method3 method2 method2 method1 method1 method1 main method main method main method main method 2. If the exception type is Exception2, method2 is aborted, control is returned to method1, and the exception is caught by the catch block for ex2 in method1. statement3 is skipped. statement4 is executed 3. If the exception type is Exception1, method1 is aborted, control is returned to main, and the exception is caught by the catch block for ex1 in main. statement1 is skipped. statement2 is executed 4. If the exception type is not caught in method2, method1, or main, the program terminates, and statement1 and statement2 are not executed 16 rights reserved.
9 Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception, you must invoke it in a try-catch block or declare to throw the exception in the calling method Example: void p2() throws IOException { if (file closed) throw new IOException("File is closed"); If p1() invokes p2() then we must write code as shown in (a) or (b) void p1() { p2(); catch (IOException ex) {... (a) void p1() throws IOException { rights reserved. p2(); (b) 17 Example: Declaring/Throwing/Catching Checked Exception This example demonstrates declaring, throwing, and catching exceptions by modifying the setradius() in the Circle class defined in Chapter 9 The new setradius() throws an exception if radius is negative CircleWithException TestCircleWithException rights reserved. 18
10 Rethrowing Exceptions An exception handler can rethrow the exception if the handler can t process the exception or simply wants to let its caller be notified of the exception // statements catch(theexception ex) { // perform some operations throw ex; The catch block first catches and processes the exception, and then rethrows it to the caller so that other handlers in the caller get a chance to process ex rights reserved. 19 The finally Block The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or whether an exception is caught if it occurs statements; catch(theexception ex) { finally { finalstatements; rights reserved. 20
11 animation Trace a Program Execution statements; catch(theexception ex) { finally { finalstatements; Next statement; Suppose no exceptions in the statements rights reserved. 21 animation Trace a Program Execution statements; catch(theexception ex) { finally { finalstatements; The final block is always executed Next statement; rights reserved. 22
12 animation Trace a Program Execution statements; catch(theexception ex) { finally { finalstatements; Next statement in the method is executed Next statement; rights reserved. 23 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { finally { finalstatements; Suppose an exception of type Exception1 is thrown in statement2 Next statement; rights reserved. 24
13 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { finally { finalstatements; The exception is handled. Next statement; rights reserved. 25 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { finally { finalstatements; The final block is always executed. Next statement; rights reserved. 26
14 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { finally { finalstatements; The next statement in the method is now executed. Next statement; rights reserved. 27 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { catch(exception2 ex) { throw ex; finally { finalstatements; statement2 throws an exception of type Exception2. Next statement; rights reserved. 28
15 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { catch(exception2 ex) { throw ex; finally { finalstatements; Handling exception Next statement; rights reserved. 29 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { catch(exception2 ex) { throw ex; finally { finalstatements; Execute the final block Next statement; rights reserved. 30
16 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { catch(exception2 ex) { throw ex; finally { finalstatements; Rethrow the exception and control is transferred to the caller Next statement; rights reserved. 31 CS 112 Programming 2 Lecture 09 Exception Handling & Text I/O (2)
17 First Midterm Exam Monday, 29 February (same time as the lecture) 75 minute duration Will cover all lectures delivered before the exam date Will consist of MCQ s, fill-in-the-blanks, questions with short answers, programming tasks, and drawing of diagrams If you miss this exam for any reason, you will have to appear for a makeup exam on the Thursday of the last week of teaching (5 May). That exam will cover al lectures delivered in the semester. It will consist of programming tasks, drawing of diagrams and answering questions having page answers Pros & Cons of Exception Handling Advantage: Code is easier to understand and modify Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify Drawback: Slower performance, higher resource requirement Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods rights reserved. 34
18 When to Use Exceptions Handling? Use try-catch blocks to deal with unexpected error conditions Do not use them to deal with simple, expected situations Example: 2 nd block of code is preferable over the 1 st System.out.println(refVar.toString()); catch (NullPointerException ex) { System.out.println("refVar is null"); if (refvar!= null) System.out.println(refVar.toString()); else System.out.println("refVar is null"); rights reserved. 35 When to Throw Exceptions? When an exception occurs in a method, if we want the exception to be processed by its caller, we should create an exception object and throw it if we can handle the exception in the method where it occurs, there is no need to throw it rights reserved. 36
19 Custom Exception Classes Define custom exception classes only if Java s predefined built-in classes are not sufficient Define custom exception classes by extending Exception or a subclass of Exception rights reserved. 37 Example: Custom Exception Class In Listing 12.7, setradius() throws an exception if the radius is negative. Suppose you wish to pass the radius to the handler, you have to create a custom exception class InvalidRadiusException CircleWithRadiusException TestCircleWithRadiusException rights reserved. 38
20 The File Class The File class contains the methods for obtaining the properties of a file/directory and for renaming and deleting a file/directory File is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion File is a wrapper class for the filename and its directory path A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing content from/to a file rights reserved. 39 The File Class rights reserved. 40
21 Example: Explore File Properties Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the File class to obtain their properties. The following figures show a sample run of the program on Windows and on Unix. TestFileClass rights reserved. 41 Text I/O A File object does not contain the methods for reading/ writing content from/to a file In order to perform I/O, you need to create objects using appropriate Java I/O classes We can read/write strings and numeric values from/to a text file using Scanner and PrintWriter class objects rights reserved. 42
22 Writing Data Using PrintWriter java.io.printwriter +PrintWriter(filename: String) +print(s: String): void +print(c: char): void +print(carray: char[]): void +print(i: int): void +print(l: long): void +print(f: float): void +print(d: double): void +print(b: boolean): void Also contains the overloaded println methods. Also contains the overloaded printf methods. Creates a PrintWriter for the specified file. Writes a string. Writes a character. Writes an array of character. Writes an int value. Writes a long value. Writes a float value. Writes a double value. Writes a boolean value. A println method acts like a print method; additionally it prints a line separator. The line separator string is defined by the system. It is \r\n on Windows and \n on Unix. The printf method was introduced in 4.6, Formatting Console Output and Strings. WriteData rights reserved. 43 try-with-resources Programmers often forget to close the file. JDK 7 provides the following try-with-resources syntax that automatically closes files try (declare and create resources) { Use the resource to process the file; WriteDataWithAutoClose rights reserved. 44
23 Reading Data Using Scanner java.util.scanner +Scanner(source: File) +Scanner(source: String) +close() +hasnext(): boolean +next(): String +nextbyte(): byte +nextshort(): short +nextint(): int +nextlong(): long +nextfloat(): float +nextdouble(): double +usedelimiter(pattern: String): Scanner Creates a Scanner object to read data from the specified file. Creates a Scanner object to read data from the specified string. Closes this scanner. Returns true if this scanner has another token in its input. Returns next token as a string. Returns next token as a byte. Returns next token as a short. Returns next token as an int. Returns next token as a long. Returns next token as a float. Returns next token as a double. Sets this scanner s delimiting pattern. ReadData rights reserved. 45 Example: PrintWriter & Scanner Objective: Write a class named ReplaceText that replaces a string in a text file with a new string. The filename and strings are passed as command-line arguments as follows: java ReplaceText sourcefile targetfile oldstring newstring For example, invoking java ReplaceText s.txt t.txt apple orange replaces all the occurrences of apple by orange in s.txt and saves the new file in t.txt ReplaceText rights reserved. 46
24 Reading Data from the Web Just like we can read data from a file on your computer, we can also read data from a file on the Web rights reserved. 47 Reading Data from the Web URL url = new URL(" After a URL object is created, you can use openstream() defined in the URL class to open an input stream and use this stream to create a Scanner object as follows: Scanner input = new Scanner(url.openStream()); ReadFileFromURL rights reserved. 48
25 Case Study: Web Crawler Web Crawler: Program that traverses the Web by following URLs rights reserved. 49 Case Study: Web Crawler To ensure that each URL is traversed only once, the Web crawler maintains two lists of URLs: 1. List of URLs pending for traversing 2. List of URLs that have already been traversed Add the starting URL to a list named listofpendingurls; while!listofpendingurls.isempty() && listoftraversedurls.size()<= 100 { Remove a URL from listofpendingurls; if this URL is not in listoftraversedurls { Add it to listoftraversedurls; Display this URL; Read the page from this URL & for each URL contained in the page { Add it to listofpendingurls if it is not in listoftraversedurls; WebCrawler rights reserved. 50
Chapter 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 informationMotivations. Chapter 12 Exceptions and File Input/Output
Chapter 12 Exceptions and File Input/Output CS1: Java Programming Colorado State University Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the
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 informationException Handling. CSE 114, Computer Science 1 Stony Brook University
Exception Handling CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation When a program runs into a exceptional runtime error, the program terminates abnormally
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 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 informationC17a: Exception and Text File I/O
CISC 3115 TY3 C17a: Exception and Text File I/O Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/11/2018 CUNY Brooklyn College 1 Outline Discussed Error and error handling
More informationException-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 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 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 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 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 informationWhat is a Computer? Chapter 1-9, 12-13, 18, 20, 23 Review Slides
Chapter 1-9, 12-13, 18, 20, 23 Review Slides What is a Computer? A computer consists of a CPU, memory, hard disk, floppy disk, monitor, printer, and communication devices. CS1: Java Programming Colorado
More informationChapter 1-9, 12-13, 18, 20, 23 Review Slides. What is a Computer?
Chapter 1-9, 12-13, 18, 20, 23 Review Slides CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox rights reserved. 1 What is a Computer? A computer
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 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 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 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. 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 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 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 informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationInput-Output and Exception Handling
Software and Programming I Input-Output and Exception Handling Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Reading and writing text files Exceptions The try block catch and finally
More informationCS159. Nathan Sprague
CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************
More informationabstract binary class composition diamond Error Exception executable extends friend generic hash implementation implements
CS365 Midterm 1) This exam is open-note, open book. 2) You must answer all of the questions. 3) Answer all the questions on a separate sheet of paper. 4) You must use Java to implement the coding questions.
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 informationSri Vidya College of Engineering & Technology Question Bank
1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.
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 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 informationException Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.
Exception Handling General idea Checked vs. unchecked exceptions Semantics of throws try-catch Example from text: DataAnalyzer Exceptions [Bono] 1 Announcements Lab this week is based on the textbook example
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 informationObject Oriented Programming. Week 7 Part 1 Exceptions
Object Oriented Programming Week 7 Part 1 Exceptions Lecture Overview of Exception How exceptions solve unexpected occurrences Catching exceptions Week 7 2 Exceptions Overview Week 7 3 Unexpected Occurances
More informationCS 3 Introduction to Software Engineering. 3: Exceptions
CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction
More informationCOSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan
COSC 123 Computer Creativity I/O Streams and Exceptions Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Objectives Explain the purpose of exceptions. Examine the try-catch-finally
More informationExceptions. Examples of code which shows the syntax and all that
Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces
More informationing execution. That way, new results can be computed each time the Class The Scanner
ing execution. That way, new results can be computed each time the run, depending on the data that is entered. The Scanner Class The Scanner class, which is part of the standard Java class provides convenient
More informationPages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.
CS511, HANDOUT 12, 7 February 2007 Exceptions READING: Chapter 4 in [PDJ] rationale for exceptions in general. Pages 56-63 and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines
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 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 informationCOE318 Lecture Notes Week 10 (Nov 7, 2011)
COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:
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 informationChapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions
Chapter 15 Exception Handling Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference between checked and unchecked exceptions To learn
More informationReading Input from Text File
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 5 Reading Input from Text File Eng. Mohammed Alokshiya November 2, 2014 The simplest
More information11/1/2011. Chapter Goals
Chapter Goals To be able to read and write text files To learn how to throw exceptions To be able to design your own exception classes To understand the difference between checked and unchecked exceptions
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 informationExceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15
s Computer Science and Engineering College of Engineering The Ohio State University Lecture 15 Throwable Hierarchy extends implements Throwable Serializable Internal problems or resource exhaustion within
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
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 informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (IS120) Lecture 30 April 4, 2016 Exceptions hapter 27 HW7: PennPals hat Due: Tuesday Announcements Simplified Example class { public void foo() {.bar(); "here in foo");
More informationEXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {
EXCEPTION HANDLING We do our best to ensure program correctness through a rigorous testing and debugging process, but that is not enough. To ensure reliability, we must anticipate conditions that could
More informationCS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events
CS1020 Data Structures and Algorithms I Lecture Note #8 Exceptions Handling exceptional events Objectives Understand how to use the mechanism of exceptions to handle errors or exceptional events that occur
More informationExceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology
Exceptions Algorithms 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 Exceptions ± Definition
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 informationErrors and Exceptions
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 An exception isn t necessarily your fault trying
More informationDefensive Programming. Ric Glassey
Defensive Programming Ric Glassey glassey@kth.se Outline Defensive Programming Aim: Develop the programming skills to anticipate problems beyond control that may occur at runtime Responsibility Exception
More informationJava Exception. Wang Yang
Java Exception Wang Yang wyang@njnet.edu.cn Last Chapter Review A Notion of Exception Java Exceptions Exception Handling How to Use Exception User-defined Exceptions Last Chapter Review Last Chapter Review
More informationExceptions Handling Errors using Exceptions
Java Programming in Java Exceptions Handling Errors using Exceptions Exceptions Exception = Exceptional Event Exceptions are: objects, derived from java.lang.throwable. Throwable Objects: Errors (Java
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 information17. Handling Runtime Problems
Handling Runtime Problems 17.1 17. Handling Runtime Problems What are exceptions? Using the try structure Creating your own exceptions Methods that throw exceptions SKILLBUILDERS Handling Runtime Problems
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationCC316: Object Oriented Programming
CC316: Object Oriented Programming Lecture 5: Strings and Text I/O - Ch 9. Dr. Manal Helal, Fall 2015. http://moodle.manalhelal.com Motivations Often you encounter the problems that involve string processing
More informationIntroduction Unit 4: Input, output and exceptions
Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.
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 informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationExceptions, Case Study-Exception handling in C++.
PART III: Structuring of Computations- Structuring the computation, Expressions and statements, Conditional execution and iteration, Routines, Style issues: side effects and aliasing, Exceptions, Case
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 informationIntro to Computer Science II. Exceptions
Intro to Computer Science II Exceptions Admin Exam review Break from Quizzes lab questions? JScrollPane JScrollPane Another swing class Allows a scrollable large component. JList? Constructors See next
More informationException Handling in Java
Exception Handling in Java The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the runtime errors so that normal flow of the application can be
More informationFull file at Chapter 2 - Inheritance and Exception Handling
Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a
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 informationI/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1
File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department
More informationI/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1
File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department
More information14. Exception Handling
14. Exception Handling 14.1 Intro to Exception Handling In a language without exception handling When an exception occurs, control goes to the operating system, where a message is displayed and the program
More information16-Dec-10. Consider the following method:
Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to
More informationCS Programming I: Exceptions
CS 200 - Programming I: Exceptions Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624 Command-Line
More informationSchool of Informatics, University of Edinburgh
CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions
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 informationInternal Classes and Exceptions
Internal Classes and Exceptions Object Orientated Programming in Java Benjamin Kenwright Outline Exceptions and Internal Classes Why exception handling makes your code more manageable and reliable Today
More informationGPolygon GCompound HashMap
Five-Minute Review 1. How do we construct a GPolygon object? 2. How does GCompound support decomposition for graphical objects? 3. What does algorithmic complexity mean? 4. Which operations does a HashMap
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 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 informationCOMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others
COMP-202 Exceptions Lecture Outline Exceptions Exception Handling The try-catch statement The try-catch-finally statement Exception propagation Checked Exceptions 2 Exceptions An exception is an object
More informationObject Oriented Programming
Object Oriented Programming Java lecture (10.2) Exception Handling 1 Outline Throw Throws Finally 2 Throw we have only been catching exceptions that are thrown by the Java run-time system. However, it
More informationWhy Exceptions? (1.1) Exceptions. Why Exceptions? (1.2) Caller vs. Callee. EECS2030 B: Advanced Object Oriented Programming Fall 2018
Why Exceptions? (1.1) Exceptions EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG 1 class Circle { 2 double radius; 3 Circle() { /* radius defaults to 0 */ 4 void setradius(double
More informationExceptions. EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG
Exceptions EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG Caller vs. Callee Within the body implementation of a method, we may call other methods. 1 class C1 { 2 void m1() { 3
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 30 November 13, 2015 ExcepEons / IO Chapter 27 HW7: PennPals Chat Due: Tuesday, November 17 th Announcements Start today if you haven't already! Poll
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 informationExceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions
Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate
More informationIntroductory Programming Exceptions and I/O: sections
Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate
More informationJava Errors and Exceptions. Because Murphy s Law never fails
Java Errors and Exceptions Because Murphy s Law never fails 1 Java is the most distressing thing to hit computing since MS-DOS. Alan Kay 2 Corresponding Book Sections Pearson Custom Computer Science: Chapter
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 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 informationProgram Correctness and Efficiency. Chapter 2
Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you
More informationComp 249 Programming Methodology Chapter 9 Exception Handling
Comp 249 Programming Methodology Chapter 9 Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted,
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 informationCS159. Nathan Sprague
CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the maximum, or Integer. MIN_VALUE 3 * if the array has length 0. 4 ***************************************************
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 informationCS 11 java track: lecture 3
CS 11 java track: lecture 3 This week: documentation (javadoc) exception handling more on object-oriented programming (OOP) inheritance and polymorphism abstract classes and interfaces graphical user interfaces
More information