LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.

Slides:



Advertisements
Similar presentations
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Advertisements

Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
CSC 212 – Data Structures Lecture 10: More Inheritance & Exceptions.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
11-Jun-15 Exceptions. 2 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.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
CIS 270—Application Development II Chapter 13—Exception Handling.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
COMP Exception Handling Yi Hong June 10, 2015.
Question of the Day  A landscaper plants 5 rows of 4 trees each, but only uses 10 trees. How is this possible?
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Question of the Day completes starts  What word completes the 1 st word & starts the 2 nd one: DON???CAR.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
COP 3330 Notes 3/7. Today’s Topics Exceptions Abstract Classes.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Chapter 13 Exception Handling
Exceptions, Interfaces & Generics
CSE 116/504 – Intro. To Computer Science for Majors II
Introduction to Exceptions in Java
Exceptions 10-Nov-18.
ATS Application Programming: Java Programming
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Exceptions 10-May-19.
Java Basics Exception Handling.
Presentation transcript:

LECTURE 8: EXCEPTIONS CSC 212 – Data Structures

Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May want to execute code to handle to fix error  Minimize amount of rewritten code  May want to change in subclass  Future inputs & uses of code should be considered  Changing printing of error message is not possible

Exceptional Circumstances  ex-cep-tion : n.  Instance or case not conforming to the general rule  Proper way to signal error in object-oriented code  Seen Java exceptions in CSC111 already  Most are unchecked exceptions (no real solution)  ArrayIndexOutOfBoundsException -- accessing a nonexistent array entry  NullPointerException -- used reference that is equal to null

Exception Classes Java  Exception is a class defined by Java  Java defines many subclasses of Exception  New Exception subclasses can be written, also  Error handling uses instances of these classes  Classes are no different than others  Will include fields, methods, & constructors  Exception instances are normal objects  Use anywhere, not strictly for error handling  Must instantiate before use

Throwing an Exception public class BankAccount { private float balance; // Lots of code here… float withdraw(float amt) throws ReqException{ if (amt balance) { ReqException re = new ReqException(); re.setBadRequest(amt, balance); throw re; } balance -= amt; return balance; } }

Error Handling Codes  throw exception upon detecting problem  Handle problem by catch ing exception  Do not need to catch an exceptions  If it is never caught, program will crash  Not a bad thing – had an unfixable error!

Handling Exceptions  Once an exception is thrown, methods can:  Include code to catch exception and then ignore it

Handling Exceptions  Once an exception is thrown, methods can:  Include code to catch exception and then ignore it  Catch & handle exception so error is fixed

Handling Exceptions  Once an exception is thrown, methods can:  Include code to catch exception and then ignore it  Catch & handle exception so error is fixed  Catch the exception and throw a new one

Handling Exceptions  Once an exception is thrown, methods can:  Include code to catch exception and then ignore it  Catch & handle exception so error is fixed  Catch the exception and throw a new one  Ignore exception so passed on to calling method

Handling Exceptions  Exception can be thrown anywhere & anytime  throws lists method’s fixable uncaught exceptions void controller() throws LostPlane {…} int scheduler() throws NoFreeTime {…}  Calling methods now aware of possible errors  If possible, could catch and correct errors  List exception in own throws clause otherwise void plan(int i) throws NoFreeTime { // Lots of interesting code here… scheduler(); }

try {…} Blocks  Cannot catch exceptions thrown outside try block void cantCatch() throws Oops, MyBadExcept { try { // There is code here that does something interesting… System.err.println(“This is not my exception”); } catch (Oops oop) { // Here be code… } methodThatMightThrowOopsExcept(); throw new MyBadExcept(); }

try {…} Blocks  Catch some (or all) exceptions thrown in try  Each try needs at least 1 catch void catchSome() throws MyBadException { try { methodThatMightThrowOops(); throw new MyBadExcept(); } catch (Oops oop) { oop.printStackTrace(); System.err.println(“Oops was caught.”); System.err.println(“Method ends normally.”); } }

try {…} Blocks  try can have multiple catch s void catchAll() { try { methodThatMightThrowOops(); methodThatShouldThrowOops(); throw new MyBadExcept(); } catch (Oops oop) { oop.printStackTrace(); System.err.println(“Oops was caught.”); System.err.println(“Method ends normally.”); } catch (MyBadExcept mbe) { mbe.printStackTrace(); System.err.println(“MyBad was caught.”); System.err.println(“Method ends normally.”); } }

Handling Exceptions public void forcedWithdrawal(float amount) throws BadRequestException { callPolice(); addDyePacks(); withdrawal(amount); } public void defeatOfJesseJames(float amt) { try { forcedWithdrawal(amt); } catch (BadRequestException bre) { formPosse(); killSomeGangMembers(); } finally { giveLollipop(); } }

2 Types of Exceptions  Subclass of Exception  Must list uncaught exceptions in throws  Use for fixable errors  Java forces methods to consider them  Only useful if fixable  Subclass of RuntimeException  Can list uncaught ones in throws  “You are hosed”  Usually can’t be fixed  Can ignore in method  Still crashes program unless it is caught Checked Exception Unchecked Exception

Tracing Example public static int generate() throws TraceException { TraceException te = new TraceException(); System.out.println(“Starting gE”); throw te; System.out.println(“Ending gE”); return 0; } public static void handler(boolean callIt) { try { System.out.println(“Starting cE”); if (callIt) { generate(); } System.out.println(“Ending cE”); } catch (TraceException te) { System.out.println(“Caught te”); } } public static void main(String[] args) { handler(false); handler(true); }

Before Next Lecture…  Continue week #3 weekly activity  Should now be able to do problems #1 & 2  Continue programming assignment #1  Assignment does not require any new material  Read about interfaces & abstract classes  (Will form the basis of the mysterious ADT)  Very important when working with GUIs  Useful way of beating inheritence