Administrivia Midterm exam: Mar 10 (in class) Interfaces vs. Abstract classes Inner classes Data views; iterators Lexical analyzers (tokenizers) Theory:

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
COMP 121 Week 5: Exceptions and Exception Handling.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
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 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions CIS 304 Intermediate Java Programming for Business.
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.
Exceptions, Errors, and all that gunk (for sure this time)
Advanced Java Course Exception Handling. Throwables Class Throwable has two subclasses: –Error So bad that you never even think about trying to catch.
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
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
1 Exceptions and error handling. 2 Java exception mechanism when an error or exceptional condition occurs, you throw an exception which is caught by an.
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.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
Exceptions1 Syntax, semantics, and pragmatics. Exception create If (some error){ throw new SomeException(”some message”); } Exceptions2.
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…
Exceptions and assertions CSE 331 University of Washington.
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.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
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.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
Introduction to Exceptions in Java CS201, SW Development Methods.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
Geoff Holmes Week 5 problems Handling Throwing Catching Multiple exceptions Finally clause Examples Exception Handling.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 13 Exception Handling
Chapter 13 Exception Handling
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
ATS Application Programming: Java Programming
Chapter 12 Exception Handling
Web Design & Development Lecture 7
Java Exceptions Dan Fleck CS211.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Exception Handling.
Presentation transcript:

Administrivia Midterm exam: Mar 10 (in class) Interfaces vs. Abstract classes Inner classes Data views; iterators Lexical analyzers (tokenizers) Theory: Bayesian spam analysis A*, admissibility, monotonicity, etc. Tools: Javadoc CVS Etc...

Definition of the Day... crock :n. [from the American scatologism crock of s***] 1. An awkward feature or programming technique that ought to be made cleaner. 2. A technique that works acceptably, but which is quite prone to failure if disturbed in the least. The Jargon File, v , Mar 1, 2003

Exceptions, Errors, Assertions, and all that...

Expecting the Unexpected Some huge fraction (30%? 50%?) of code is handling unexpected cases. Problem is that code that detects unexpected circumstance doesn’t always know what to do about it. Idea of Exceptions, et al. is to move handling of errors out to appropriate place to deal with them Nice idea in principle; very hard to get right in practice... :-P

Ideal Model... Throw + try/catch/finally public int fooMethod(int a) { if (a<0) { throw new IllegalArgumentException(“a must “ + “be non-negative, not a=“ + a); } // etc... } public void barMethod() { try { fooMethod(-37); } catch (IllegalArgumentException e) { // do something about it... }

Nastier in Practice... Distinction between “checked” and “unchecked” exceptions “Checked” == compiler checks to make sure you catch (or explicitly allow to pass through) an exception/family of exceptions “Unchecked” don’t need to be declared (e.g., IllegalArgumentException ) public void myLoader(String fname) throws IOException { FileReader in=new FileReader(fname); // do stuff to in... in.close(); }

What’s the “Real” Difference? How does the compiler know which is which?

What’s the “Real” Difference? How does the compiler know which is which? Compiler doesn’t force checks for two families of exceptions: Error and its subclasses RuntimeException and its subclasses Object Throwable ErrorException RuntimeException

When to Use Them So you could make an unchecked exception by extending Error or RuntimeException But do you want to? Problem is that checked exceptions tell you a lot about how a class/interface/type works E.g., java.io methods mostly throw checked exceptions Tells you what kind of failure modes they have Want to use checked exceptions whenever you (practically) can

When is it Practical? Some books tell you “Always used checked exceptions.” Wrong.

When is it Practical? Checked exceptions are good when the receiving code can actually do something about the problem IOExceptions Can’t open file => ask user for new file name File ends prematurely => close file, discard loaded data, ask for new file, etc. PrintException Printer out of paper => tell user to go fix paper and continue ParseException Unexpected/missing token => warn user

So What About RuntimeException ? Better for things that code can’t do much about Programming errors Precondition errors ( if (a<0) { throw... } ) Stuff that may or may not be b/c of structure of code (e.g., may be related to user input) Sometimes still useful to put in throws clause Always useful to document in API docs (javadoc) Your book says: “Never extend RuntimeException ” That’s wrong. But do be careful. Not an excuse to avoid throws clause!

Errors java.lang.Error is usually used to indicate a problem in the Java interpreter (JVM) Mostly stuff that’ll cause your program to die a hideous, painful, agonizing death anyway Class loader problems Bugs in the JVM (!) Circular code definitions (that sneak through compiler!) Out of memory Very rare that your code will need to generate one of these itself Mostly, do what you need w/ (Runtime)Exception

Assertions Assert provides a “conditional” exception Can turn on or off all assertion checks in code Mostly good for debugging Should be used for fundamental design problems in the code Stuff that should never happen E.g. public static void doit(int a) { switch a { case 0: doCase0(); break; case 1: doCase1(); break; default: assert false : “a=“ + a; }

Assertions, cont’d assert is only introduced in java 1.4+ Not in your book :-P Have to compile w/ “-source 1.4” switch When running, can turn on or off assertions java foo => assertions disabled java -ea foo => assertions enabled Can have same code work differently in “production” vs “debug” mode Good for guarding against deep logic errors “This should never happen” sorts of things

Do’s Use checked exceptions when you possibly can Provide useful messages to your exceptions Provide erroneous data when you can (helpful in debugging) IllegalArgumentException(“a should be >0”); IllegalArgumentException(“a should be >0; not a=“ + a); Use RuntimeExceptions for argument validation But document them anyway!

Don’t’s throw new Exception(“my message”) Extend Throwable (no need) Use exceptions for “normal” control flow Eeeeeeeeeeeeeevil! (Why?) int i=0; int[] a=new int[10]; try { while (true) { doSomething(a[i++]); } catch (ArrayIndexOutOfBoundsException e) {}

Chaining Exceptions Also new in Java 1.4+ Sometimes, you get an exception that doesn’t match your contract E.g., method guarantees to throw only NoSuchElementException, but gets an EOFException internally Want to “re-throw” the exception “wrapped” in the correct exception class Use the initCause() and getCause() methods Sometimes have constructors for chaining Can chain arbitrarily far

Finally, finally finally clause prevents code being “missed” by thrown exceptions throw seems to “skip” intervening code until appropriate “catch” is found Not quite right -- locally allocated objects are deallocated Any “finally” blocks are executed Use finally to be sure that certain code is executed, even if rest of code is missed by exceptions Good for non-Java resources you may have open (e.g., files, network or DB connections, etc.)