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.

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

1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
For use of Cleveland State's IST410 Students only 1 Exception.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
1 CS2200 Software Development Lectures 28: Exception Handling A. O’Riordan, 2008 (Includes some slides by Lewis/Loftus 2005 and K. Brown )
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 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  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
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.
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.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
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.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Chapter 15 – 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
Abdulmotaleb El Saddik University of Ottawa
Exception Handling and Reading / Writing Files
TRY CATCH BLOCK By Kosala Rajapaksha.
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Java Exception Very slightly modified from K.P. Chow
CSE 143 Java Exceptions 1/18/2019.
Managing Errors and Exceptions
Java Exceptions Dan Fleck CS211.
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.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Tutorial MutliThreading.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
Chapter 15 – Exception Handling
Presentation transcript:

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

Outline for Today What is an Exception? How to Catch Exceptions checked v. unchecked How to Catch Exceptions examples of good and bad try-catch code Creating your own types of Exception declaring your new exception throwing your new exception

Definition An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program.

Sample Exceptions ArithmeticException ArrayStoreException when a divide by zero is attempted ArrayStoreException trying to put an int into a float array IndexOutOfBoundsException accessing invalid array or string element ArrayIndexOutOfBoundsException subclass of IndexOutofBoundsException accessing invalid array element NegativeArraySizeException obvious NullPointerException when you try to dereference a null object reference

Part of the Exception Class Hierarchy Throwable Error Exception ClassNotFoundException InstantiationException IOException FileNotFoundException EOFException RuntimeException ArithmeticException ClassCastException IllegalArgumentException IllegalThreadStateException NumberFormatException NullPointerException

Types of Exceptions Error Exception checked unchecked example - OutOfMemoryError Exception checked example - FileNotFoundException unchecked example - ArrayIndexOutOfBoundsException "checked" must be handled "unchecked" are usually not dealt with directly all "errors" are "unchecked"

How Exceptions are Propagated When a statement produces an exception (checked or unchecked) and the statement is not inside a try statement, then the exception is thrown up to whoever called this piece of code. If that calling function does not catch the exception, the exception is passed up to whoever called this function. etc etc etc If main throws an exception, then the JVM prints the calling stack and exits the program.

The throws Statement "Checked" exceptions must be dealt with. If a statement can produced a checked exception that statement must either be inside a try statement or the method must pass the possible exception up to the calling method via throws. public static void main(String[] args) throws IOException { code for reading or writing that is not inside a try statement }

Catching Exceptions try { code that might throw an exception } catch (ExceptionName param) code used when this error occurs catch (AnotherExceptionName param) { yadda yadda } finally do this code, no matter if error occurs

Example 1 - File Opening // open the data file for reading try { FileReader freader = new FileReader(fname); inputFile = new BufferedReader(freader); } catch (FileNotFoundException e) System.out.println("Unknown File: " + fname); return; catch (IOException e) System.out.println("Error Opening " + fname); Note: the order of these two exceptions is important

Example 2.1 - Converting String to Integer Version One - Crashes on Bad Input // read until eof and sum the values dataline = inputFile.readLine(); while (dataline != null) { nextint = Integer.parseInt(dataline); sum += nextint; }

Example 2.2 - Converting String to Integer Version Two - Sum is Wrong // read until eof and sum the values dataline = inputFile.readLine(); while (dataline != null) { try nextint = Integer.parseInt(dataline); } catch (NumberFormatException nfe) System.out.println("unable to ... sum += nextint;

Example 2.3 - Converting String to Integer Version Three - Infinite Loop // read until eof and sum the values dataline = inputFile.readLine(); while (dataline != null) { try nextint = Integer.parseInt(dataline); sum += nextint; } catch (NumberFormatException nfe) System.out.println("unable to ...

Example 2.4 - Converting String to Integer // read until eof and sum the values dataline = inputFile.readLine(); while (dataline != null) { try nextint = Integer.parseInt(dataline); sum += nextint; } catch (NumberFormatException nfe) System.out.println("unable to convert \"" + nfe.getMessage() + "\" into an integer");

Creating Your Own Exceptions Suppose you are writing a stack class. Then you will want to create your own exceptions. StackException StackOverflowException StackUnderflowException StackTypeMismatchException Which existing exception class do you build your exception off of? best idea is to use Exception RuntimeException is okay

Example - new checked exception declaration of your stack class: public class StackClass { public class StackException extends Exception; {...} public class StackOverflowException extends StackException; {...} public int pop() {...} inside a method that uses your stack class: try mystack.push(8); } catch (StackOverflowException e) see code on next slide

Example - declaration details public class StackException extends Exception { StackException () super (); } StackException ( String description ) super ( description ) "super" = use my mom's constructor

How to throw an exception public class StackClass { ... // the pop method public int pop () if (stacksize == 0) throw StackUnderflowException; return list [ --stacksize ]; }

Next Classes writing classes writing classes that extend other classes