Exceptions and Error Handling
|
|
- Joel Richardson
- 6 years ago
- Views:
Transcription
1 Exceptions and Error Handling Michael Brockway January 16, 2015
2 Some causes of failures Incorrect implementation does not meet the specification. Inappropriate object request invalid index. Inconsistent or inappropriate object state arising through class extension. Not always programmer error Errors often arise from the environment; for instance, incorrect URL entered network interruption File processing is particularly error-prone: missing files lack of appropriate permissions.
3 Defensive Programming In Client-server interaction. Should a server assume that clients are well-behaved? or should it assume that clients are potentially hostile? Significant differences in implementation required. Issues How much checking by a server on method calls? How to report errors? How can a client anticipate failure? How should a client deal with failure? Arguments represent a major vulnerability for a server object. Constructor arguments initialize state. Method arguments often contribute to behaviour. Argument checking is one defensive measure.
4 Checking the Argument Eg check the key is being used before removing the item... public void removedetails(string key) { if (keyinuse(key)) { ContactDetails details = book.get(key); book.remove(details.getname()); book.remove(details.getphone()); numberofentries--; Server could return a diagnostic value...
5 Diagnostic value Eg check the key is being used before removing the item... public boolean removedetails(string key) { if (keyinuse(key)) { ContactDetails details = book.get(key); book.remove(details.getname()); book.remove(details.getphone()); numberofentries--; return true; //else return false;
6 Checking the return value What should client do with the diagnostic value? Is there a human user? who can solve the problem? The client object could test the return value attempt to recover or work around the error avoids program failure. The client could ignore the return value probably leads to program failure. An alternative approach is for a server function to throw an exception.
7 Exceptions A special language feature. special return value needed. Errors cannot be ignored in the client. The normal flow-of-control is interrupted. Specific recovery actions are encouraged. An exception is a problem that occurs when a program is running. Often a problem caused by circumstances outside the control of the program, such as bad user input. When an exception occurs the Java run-time creates an object of class Exception which holds information about the problem. A Java program itself may catch an exception. It can then use the Exception object to recover from the problem.
8 The Java exception mechanism A thrown exception involves transfer of control: processor stops executing current sequence of statements, and begins executing statements at a different point in the program. after the exception handler has run, the original sequence may resume. Exception is caught or handled by the code at the point to which control is transferred. There are two types of exception Checked exceptions subclass of Exception uses for anticipated failures, where recovery may be possible. Unchecked exceptions subclass of RuntimeException used for unanticipated failures, where recovery is unlikely.
9 Checked and Unchecked Exceptions Exception IOException CHECKED AWTException CHECKED RunTimeException all following subsclasses UNCHECKED ArithmeticException IllegalArgumentException NumberFormatException IndexOutOfBoundsException... others CHECKED
10 Checked and Unchecked Exceptions Unchecked exceptions are not checked by the compiler If thrown but not caught by a handler, the program terminates. Example: IllegalArgumentException Checked exceptions Some exception types are checked exceptions which means that a method must do something about them. The compiler checks each method to enforce this requirement. There are two things a method can do with a checked exception: handle the exception in a catch{ block; throw the exception to the caller of the method (which must have a handling mechanism of either of these kinds).
11 The throws clause A method in which a checked exception may be thrown must either provide code to handle the exception Use try {... catch(exception) {... as explained below or include a throws clause in its declaration: public void savetofile(string destinationfile) throws IOException { (body of method) In the latter case, when an exception occurs, control passes from the method to (the handling mechanism in) the method which called it.
12 Code can throw an exception Exceptions occur in the operating environment of a program; but they can be created by the code within the program An Exception should be used for an exceptional situation outside of the normal logic of a program Use one when the problem occurs in the middle of a complicated method that would be made even more complicated if it also had to handle unexpected data: for example, if (age < 16) { throw new Exception("Age is "+16); else { (other statements)
13 Another example /** * Look up a name or phone number and return the * corresponding contact details. key The name or number to be looked up. The details corresponding to the key, * or null if there are none matching. NullPointerException if the key is null. */ public ContactDetails getdetails(string key) { if(key == null) { throw new NullPointerException("null key in getdetails"); return book.get(key); (This is not compulsory, as the NullPointerException is unchecked.)
14 Throwing an exception When an exception is thrown by code, An exception object is constructed: just as when an exception occurs in program environment new ExceptionType("...") could be user-define sublass of Exception; The exception object is thrown: throw... Javadoc ExceptionType reason
15 Argument checking (again) public ContactDetails getdetails(string key) { if (key == null) { throw new NullPointerException("null key in getdetails"); if(key.trim().length() == 0) { throw new IllegalArgumentException ( "Empty key passed to getdetails"); return book.get(key);
16 Preventing object creation //Constructor: public ContactDetails ( String name, String phone, String address) { if (name == null) { name = "" if (phone == null){ phone = ""; if (address == null) { address = ""; this.name = name.trim(); this.phone = phone.trim(); this.address = address.trim(); if (this.name.length() == 0 && this.phone.length() == 0) { throw new IllegalStateException( "Either the name or phone must not be blank.");
17 A throws example public class DoesIO { public static void main(string[] args) throws IOException { BufferedReader stdin = new BufferedReader ( new InputStreamReader(System.in)); System.out.println("Enter an integer:"); int num = Integer.parseInt(stdin.readLine()); System.out.printf("Square of %d is %d\n", num, num*num); This method does does not catch (handle) the IOException; it is instead thrown to the method that called this one. When the java runtime receives an exception from a program, it stops the program and prints a trace of what went wrong.
18 A multilayer throws example public class BuckPassing { public static void methodc() throws IOException { //... Some I/O code public static void methodb() throws IOException { //... methodc(); public static void methoda() throws IOException { //... methodb(); public static void main (String[] a) throws IOException { methoda();
19 A multilayer throws example An IOException occurs in methodc, which is called by methodb, which is called by methoda, called by main. It is thrown by methodc to methodb, which throws it to methoda, which throws is to main, which throws it to the java run-time. The stack trace looks like java.lang.ioexception: (some message) at some Java IO method at BuckPassing.methodC at BuckPassing.methodB at BuckPassing.methodA at BuckPassing.main
20 try { and catch { Usually we do not want to just throw exceptions up to calling methods; we want our code to catch the exception and handle it. To catch an exception: Put code that might throw an exception inside a try{ block. Put code that handles the exception inside a catch{ block. If a statement inside the try{ block throws an exception, the catch{ block immediately starts running. The remaining statements in the try{ block are skipped. After the catch{ block is executed, execution continues with the statement that follows the catch{ block. Execution does not return to the try{ block.
21 try { and catch { example boolean done = false; while (!done) { System.out.print("Enter file path: "); BufferedReader stdin = new BufferedReader ( new InputStreamReader(System.in)); String filename = stdin.readline(); try { addressbook.savetofile(filename); done = true; catch (IOException e) { System.out.println("Unable to save to " + filename); If savetofile throws an IOException, control transfers to the catch block; then resumes with the code after the catch block: in this case the end of the loop.
22 Another example try { num = Integer.parseInt(stdin.readLine()); System.out.printf("Square of %d is %d\n", num, num*num); catch (NumberFormatException ex) { System.out.println("You entered bad data."); System.out.println(ex.toString()); System.out.println("Run the program again."); System.out.println("Goodbye" ); Note that the exception object has a string representation containing a useful diagnostic message.
23 try { and catch { Syntax try{ // statements, some of which might throw an exception catch (SomeExceptionType ex){ // statements to handle this type of exception // optionally more catch blocks catch (AnotherExceptionType ex){ // statements to handle this type of exception // statements following the structure Statements in the try { block can include statements that always work statements that might throw an exception of one type or another There can be one or several catch{ blocks, or none. Each catch{ block describes the type of exception it handles.
24 Operation of try { and catch { The code statements in the try { run in sequence. If a statement causes an exception, control passes to the first matching catch { block for handling. Once the exception is handled, processing resumes with the statement after the last catch { block. If there is no catch { block matching the exception (or no catch { blocks at all), the exception is thrown up to the calling function, or the program terminates. Execution leaves the current method.
25 Example with multiple Exception types and catch { blocks public static void main ( String[] a ) throws IOException {...(code to set up stdin) try { System.out.println("Enter the numerator:"); num = Integer.parseInt(stdin.readLine()); System.out.println("Enter the divisor:"); div = Integer.parseInt(stdin.readLine()); System.out.printf("%d / %d = %d\n", num, div, num/div); catch (NumberFormatException ex ) { System.out.println("Problem with numeric input:"); System.out.println(ex); catch (ArithmeticException ex ) { System.out.println("Arithmetic exception"); System.out.println(ex);
26 Comments on the Example An IOException might occur in either readline() statement. There is no catch{ block for this type of exception, so the method has to say throws IOException. A NumberFormatException might occur in either call to parseint(). The input string is not a valid integer. The first catch{ block is for this type of exception. It will catch exceptions thrown from either parseint(). An ArithmeticException might occur if the user enters data that can t be used in an integer division: eg, a zero divisor. The second a catch{ block is for this type of exception.
27 The finally{ block If an IOExeption occurs in our program, it immediately loses control. The exception is thrown to the method that called it: in this case is the Java run time system. The program execution will halt. By using a finally{ block, you can ensure that some statements will always run, no matter how the try{ block was exited.
28 The finally{ block - Structure try{ // statements, some of which might throw an exception catch (SomeExceptionType ex){ // statements to handle this type of exception // optionally more catch blocks catch ( AnotherExceptionType ex ){ // statements to handle this type of exception finally{ // statements which will execute no matter // how the try block was exited. // Statements following the structure There can be only one finally block and it must come after the catch blocks.
29 Operation of try { and catch { with finally { The code statements in the try { run in sequence. If they all run without exception, control then passes to the finally { block, and then to the statements after the try/catch/finally structure. If a statement in the try { causes an exception, control passes to the first matching catch { block for handling. Once the exception is handled, control passes to the finally { block, then processing resumes with the statement after the try/catch/finally structure. If there is no catch { block matching the exception (or no catch { blocks at all), the finally { block is executed then the exception is thrown up to the calling function.
30 Omitting catch { blocks If there is a finally { block, catch { blocks may be omitted. Do this if you don t want to handle exceptions in this method, but you have a few statements that must execute no matter what before control is returned to the caller. This often happens if a method has a lock on some resource that it should give up before exiting. For example, if the method opens a file, it should (perhaps) close it before exiting.
31 Dealing with exceptions 1. Clean up and report the failure to caller (by throwing an exception). 2. Attempt to correct the situation that caused the exception, and try again. Here is an example. The constructor of java.io.filereader has the specification public FileReader (String filename) throws FileNotFoundException, SecurityException; So method using a FileReader to get some data from a file needs a specification like public void getsomedata () throws FileNotFoundException, SecurityException { FileReader in; in = new FileReader("DataFile");...
32 Dealing with exceptions ctd Some cleanup might be appropriate before throwing the exception updstairs : public void getsomedata () throws FileNotFoundException, SecurityException { FileReader in; try { in = new FileReader("DataFile");... catch (FileNotFoundException e) { // do cleanup... throw e; // throws it again to its caller catch (SecurityException e) { //cleanup throw e; // throws it again to its caller
33 Cleanup; Retrying A method cannot know how its caller will respond to the exception. The caller might be able to recover. It is important that method leave object in a consistent state (with all class invariants satisfied). The method should make sure that object is consistent before reporting failure to caller. The following code indicates how you might throw an exception up to the calling function only after a number of retries...
34 The FileReader example, ctd public void getsomedata () throws FileNotFoundException, SecurityException { FileReader in; boolean success = false; //Data file opened int trynum = 0, maxtries = 5; int delay = 5000; //msec while (!success) { try { trynum++; in = new FileReader("DataFile"); success = true;... catch (SecurityException e) { // we might expect if (trynumb < maxtries) //file lock to be Thread.sleep(delay); //removed shortly else throw e;
35 Exception Objects Exceptions are objects of class Exception or a subclass of it. They have member data and member methods, including: public void printstacktrace(): prints a stack trace: a list that shows the sequence of method calls up to this exception; public String getmessage(): returns a string that may describe what went wrong A catch{ block can use these methods to write an informative error message to the monitor
36 Application-defined Exceptions We can define our own exception classes to pass information to user/client. Example: throw exception if fail to get data: public class NoDataException extends Exception { public NoDataException () { //constructor super(); public NoDataException (String s) { //another constructor super(s);
37 Using NoDataException public void getsomedata () throws NoDataException { try { in = new FileReader("DataFile");... catch (FileNotFoundException e) { //cleanup throw new NoDataException ("File does not exist"); catch (SecurityException e) { //cleanup throw new NoDataException ("File cannot be accessed");
38 Another Application-defined Exception An exception class can pass state information from the method detecting the exception to the method that handles it: public class BadDataException extends Exception { private int linenumber; public BadDataException (int linenumber){ super(); this.linenumber = linenumber; public int linenumber() { return this.linenumber;
39 Error recovery Clients should take note of error notifications: check return values; do not ignore exceptions. Include code to attempt recovery: this will often require a loop. For example...
40 Error recovery // Try to save the address book. boolean successful = false; int attempts = 0; do { try { addressbook.savetofile(filename); successful = true; catch (IOException e) { System.out.println("Unable to save to " + filename); attempts++; if (attempts < MAX_ATTEMPTS) { filename = altfilename; while (!successful && attempts < MAX_ATTEMPTS); if(!successful) { [Report the problem and give up];
41 Summary Runtime errors arise for many reasons. An inappropriate client call to a server object. A server unable to fulfill a request. Programming error in client and/or server. Runtime errors often lead to program failure. Defensive programming anticipates errors in both client and server. Exceptions provide a reporting and recovery mechanism.
Main concepts to be covered. Handling errors. Some causes of error situations. Not always programmer error. Defensive programming.
Main concepts to be covered Handling errors Or, When Bad Things Happen to Good Programs Defensive programming. Anticipating that things could go wrong. Exception handling and throwing. Error reporting.
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 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 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 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 Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked
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 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 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. 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 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 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 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 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 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 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 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 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 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 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 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. 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 informationC16b: Exception Handling
CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1 Outline Exceptions Catch and handle exceptions (try/catch)
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 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 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 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 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 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 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 informationWhat is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked
What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked exceptions Java try statement Final wishes Java try-resource
More informationWhat are Exceptions?
Exception Handling What are Exceptions? The traditional approach Exception handing in Java Standard exceptions in Java Multiple catch handlers Catching multiple exceptions finally block Checked vs unchecked
More informationIntroduction to Computer Science II CS S-22 Exceptions
Introduction to Computer Science II CS112-2012S-22 Exceptions David Galles Department of Computer Science University of San Francisco 22-0: Errors Errors can occur in program Invalid input / bad data Unexpected
More informationCS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down
CS112-2012S-22 Exceptions 1 22-0: Errors Errors can occur in program Invalid input / bad data Unexpected situation Logic error in code Like to handle these errors gracefully, not just halt the program
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 informationExceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws
Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,
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 information9. Java Errors and Exceptions
Errors and Exceptions in Java 9. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,
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 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 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 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 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 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 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 information6. Java Errors and Exceptions
Errors and Exceptions in Java 6. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,
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 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 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 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 information6. Java Errors and Exceptions. Errors, runtime-exceptions, checked-exceptions, exception handling, special case: resources
129 6. Java Errors and Exceptions Errors, runtime-exceptions, checked-exceptions, exception handling, special case: resources Errors and Exceptions in Java 130 Errors and exceptions interrupt the normal
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 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 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 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 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 informationTo Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));
A student adds a JUnit test: To Think About @Test public void mogrifytest() { assertequals("mogrify fails", new int[] { 2, 4, 8, 12 }, MyClass.mogrify(new int[] { 1, 2, 4, 6 })); } The test always seems
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 informationCSE 143 Java. Exceptions 1/25/
CSE 143 Java Exceptions 1/25/17 12-1 Verifying Validity of Input Parameters A non-private method should always perform parameter validation as its caller is out of scope of its implementation http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html
More informationEXCEPTION-HANDLING INTRIVIEW QUESTIONS
EXCEPTION-HANDLING INTRIVIEW QUESTIONS Q1.What is an Exception? Ans.An unwanted, unexpected event that disturbs normal flow of the program is called Exception.Example: FileNotFondException. Q2.What is
More informationException in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.
Exceptions 1 Handling exceptions A program will sometimes inadvertently ask the machine to do something which it cannot reasonably do, such as dividing by zero, or attempting to access a non-existent array
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 informationChecked and Unchecked Exceptions in Java
Checked and Unchecked Exceptions in Java Introduction In this article from my free Java 8 course, I will introduce you to Checked and Unchecked Exceptions in Java. Handling exceptions is the process by
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 informationAbstract Classes, Exceptions
CISC 370: Inheritance, Abstract Classes, Exceptions June 15, 1 2006 1 Review Quizzes Grades on CPM Conventions Class names are capitalized Object names/variables are lower case String.doStuff dostuff();
More informationExceptions. What exceptional things might our programs run in to?
Exceptions What exceptional things might our programs run in to? Exceptions do occur Whenever we deal with programs, we deal with computers and users. Whenever we deal with computers, we know things don
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 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 informationCISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.
CISC-124 20180215 These notes are intended to summarize and clarify some of the topics that have been covered recently in class. The posted code samples also have extensive explanations of the material.
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 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 and assertions
Exceptions and assertions CSE 331 University of Washington Michael Ernst Failure causes Partial failure is inevitable Goal: prevent complete failure Structure your code to be reliable and understandable
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 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 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 informationLecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.
Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws By the end of this lecture, you will be able to differentiate between errors, exceptions, and
More information7. Java Input/Output. User Input/Console Output, File Input and Output (I/O)
116 7. Java Input/Output User Input/Console Output, File Input and Output (I/O) 117 User Input (half the truth) e.g. reading a number: int i = In.readInt(); Our class In provides various such methods.
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 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 informationHere is a hierarchy of classes to deal with Input and Output streams.
PART 15 15. Files and I/O 15.1 Reading and Writing Files A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data
More information