CSE 143 Java Exceptions 1/18/2019.

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 Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
(c) University of Washington11-1 CSC 143 Java More on Exceptions Reading: Ch. 15.
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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
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
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—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.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
COMP Exception Handling Yi Hong June 10, 2015.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
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.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Introduction to Exceptions in Java CS201, SW Development Methods.
Java Exceptions a quick review….
Generics, Exceptions and Undo Command
Tirgul 13 Exceptions 1.
Chapter 13 Exception Handling
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Chapter 14: 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.
Chapter 12 Exception Handling
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Web Design & Development Lecture 7
Chapter 13 Exception Handling
Lecture 11 Objectives Learn what an exception is.
Java Exceptions Dan Fleck CS211.
CSC 143 Java More on Exceptions.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
CSC 143 Java Errors and Exceptions.
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.
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

CSE 143 Java Exceptions 1/18/2019

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 /** @param rate refresh rate, in frames per second. * @throws IllegalArgumentException if rate <= 0 or * rate > MAX_REFRESH_RATE. */ public void setRefreshRate(int rate) { // Enforce specified precondition in public method if (rate <= 0 || rate > MAX_REFRESH_RATE) throw new IllegalArgumentException("Illegal rate: " + rate); setRefreshInterval(1000/rate); } Preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions 1/18/2019

Exception Handling Exceptions: represent unusual events (as well as errors) Finite table is full; cannot add new element Attempt to open a file failed Problems: the method that detects the error does not know how to handle it (and probably should not) the client code could handle the error, but is not in a position to detect it Solution: method detecting an error throws an exception; client code catches and handles it 1/18/2019

Exceptions as Part of Method Specifications What should a client code method do with exception? Either must handle it void readSomeStuff( ) { try { readIt( ); // potentially throws an Exception } catch (Exception e) { handle Or declare that it can potentially throw it void readSomeStuff( ) throws Exception { readIt( ); 1/18/2019

try-catch try { somethingThatMightBlowUp( ); } catch (Exception e) { recovery code – e, the exception object, is a “parameter” } Execute try block If an exception is thrown, catch block can either process the exception, re-throw it, or throw another exception Thrown exceptions terminate throwing method and all methods that called it, until reaching a method that catches the exception (has a catch block whose type matches the exception) If there is no try/catch  terminate the thread (possibly the program) 1/18/2019

try-catch Can have several catch blocks try {attemptToReadFile( );} catch (FileNotFoundException e) {…} catch (IOException e) {…} catch (Exception e) { …} Semantics: try to match exception parameters in order until one matches Need to go from more specific to more general (why?) If no match – exception propagates (gets thrown) to calling method In Java SE 7 and later, a single catch block can handle more than one type of exception : catch (FileNotFoundException | IOException | Exception e) {…} http://www.oracle.com/technetwork/articles/java/java7exceptions-486908.html 1/18/2019

Throwable/Exception Hierarchy Checked Unchecked 1/18/2019

Checked vs Unchecked Exceptions Checked: are exceptions that are checked at the compile time Represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files) Are subclasses of Exception Method must establish a policy for all checked exceptions thrown by its implementation either handle them somehow  catch all checked exceptions it might encounter (try-catch) or pass the checked exceptions further up the stack  declare that it might throw them (using throws keyword) 1/18/2019

Checked vs Unchecked Exceptions Unchecked: are not checked at the compile time. Represent defects in the program (bugs) Reflect errors in program's logic from which it is not possible to recover at a run time Often invalid arguments passed to a non-private method. Are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException Method is NOT obliged to establish a policy for the unchecked exceptions thrown by its implementation (almost always does not do so) In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. 1/18/2019

Checked vs Unchecked Exceptions No need to declare anything about unchecked exceptions Include an @throws in the JavaDocs for ones specifically thrown RuntimeException (unchecked) is itself a subclass of Exception (checked). Why to have both types? http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html http://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_16.html More details on http://www.javamadesoeasy.com/2015/05/exceptions-top-60-interview-questions_16.html 1/18/2019

Writing your own exception /** Represents an exception thrown when an invalid value is given for radius */ public class InvalidRadiusException extends RuntimeException { /** * {@inheritDoc} public InvalidRadiusException(String message) { super(message); } Is this checked or unchecked exception? 1/18/2019

What can we do with InvalidRadiusException? public class Circle extends AbstractShape { /** * Given a pin and a radius greater than 0, creates a circle * @param pin the location of this circle's pin * @param radius this circle's radius. The radius must be greater than 0 * @throws InvalidRadiusException if the radius is negative or zero public Circle(Posn pin, Integer radius) { super(pin); if (radius <= 0) { throw new InvalidRadiusException("Radius must be > 0, given: " + radius); } this.radius = radius; } // elided code 1/18/2019

Always be VERY descriptive in your error message Do we need to handle it? Since InvalidRadiusException is unchecked (why?), we may or may not handle it Example of how to handle: Somewhere inside VERY important client code: try { Circle myCircle = new Circle(new Pin(0,0), -2); } catch (InvalidRadiusException invalidRadius) { ShowErrorMEssage errorMessage = new ShowErrorMessage ( "We detected an incorrect value " + "for myCircle. “ + "Please provide a positive number."); new Window(errorMessage).exit(); Always be VERY descriptive in your error message 1/18/2019