Exception Handling Part 2: Creating and Throwing Exceptions CSIS 3701: Advanced Object Oriented Programming.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
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.
COMP 121 Week 5: Exceptions and Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
CS203 Java Object Oriented Programming Errors and Exception Handling.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
The Java Inheritance Hierarchy CSIS 3701: Advanced Object Oriented Programming.
COMP Exception Handling Yi Hong June 10, 2015.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
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.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Unit Testing Part 2: Drivers and Stubs
Copyright © Curt Hill Error Handling in Java Throwing and catching 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.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
(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.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
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.
Introduction to Exceptions in Java CS201, SW Development Methods.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
© 2001 by Ashby M. Woolf Revision 2 Exceptions for Exceptional Circumstances Passing a Problem up the Chain of Command.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Generics, Exception and Undo Command. A Generic Stack Class AStack uses generic. In the main method, we have 2 instances of AStack, each type is Integer.
Java Exceptions a quick review….
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Inheritance and Encapsulation
Chapter 14: Exception Handling
Exceptions 10-Nov-18.
Chapter 12 Exception Handling
Exception Handling and Reading / Writing Files
Web Design & Development Lecture 7
CSE 143 Java Exceptions 1/18/2019.
Exceptions 10-May-19.
Java Basics Exception Handling.
Presentation transcript:

Exception Handling Part 2: Creating and Throwing Exceptions CSIS 3701: Advanced Object Oriented Programming

Validation and Exceptions Key validation question: How should your methods handle invalid states? –Prevent state change –Notify user Best approach: Throw custom exceptions –Define new exception classes –Throw when problems detected in your code

Designing Exceptions Key question: What can go wrong? NameList example: –User can add new name to full list –User can add name already in list –User can access name at nonexistent index User will get ArrayIndexOutOfBoundsException if you don’t handle! –User can construct list with non-positive size Constructors can also throw exceptions!

New Exception Classes –User can add new name to full list  FullListException –User can add name already in list  InListException –User can access name at nonexistent index  BadIndexException –User can construct list with non-positive size  NegativeListException General convention: all exception classes end with “ Exception ”

Defining Exception Classes Each exception type is a new class –Must (usually) extend RuntimeException Usually have no methods or constructors –Simply act as “flag” to throw or catch public class myexceptionException extends RuntimeException { } myexceptionException.java

Defining Exception Classes Examples: public class FullListException extends RuntimeException { } FullListException.java public class InListException extends RuntimeException { } InListException.java

Throwing Exceptions Basic syntax: throw new exceptiontype(); Note: Method exited at this point and nothing returned Construct new exception object And throw it back to caller

Throwing Exceptions Can put exception type thrown in header –Not required (except in some cases) –Very good practice Allows users to easily see what kind of exceptions hey may need to handle public returntype methodname(parameters) throws exceptiontype { …

Throwing Exceptions Example: public void add(String name) throws FullListException, InListException { if (isFull()) throw new FullListException(); if (isIn(name)) throw new InListException(); names[current] = name; current++; }

Throwing Exceptions Examples: public NameList(int max) throws NegativeListException { if (max <= 0) throw new NegativeListException(); maximum = max; current = 0; names = new String[maximum]; }

Catching and Throwing Exceptions Often catch one type of exception and then throw another type public String getNameByIndex(int index) throws BadIndexException { try {return names[index];} catch (ArrayIndexOutOfBoundsException ex) { throw new BadIndexException(); } } Adds to encapsulation of internal representation –If changed, that exception type may no longer be thrown

Adding Information to Exceptions Exception objects can contain information –Stored as member variables –Set by constructor when exception thrown –Accessed via methods when exception caught public class InListException extends RuntimeException { private String name; public InListException(String n) {name = n;} public String getName() {return name;} }

Adding Information to Exceptions Method uses constructor to set properties: public void add(String name) throws FullListException, InListException { if (isFull()) throw new FullListException(); if (isIn(name)) throw new InListException(name); names[current] = name; current++; } Information passed to constructor, stored in state variable

Adding Information to Exceptions Caller can use methods to retrieve information: public void actionPerformed(ActionEvent e) { String name = nameField.getText(); try { names.add(name); … } catch (InListException ex) { String duplicate = ex.getName(); JOptionPane.showMessageDialog(this, duplicate + " already in list"); } Call method on exception object to get information

Exception Class Hierarchy Java defines two types of exception –Exception –RuntimeException (which extends Exception ) Most commonly used exceptions extend RuntimeException

Exception Class Hierarchy Subclasses of Exception must be handled –Any statement that might cause one of these exceptions must be inside try/catch block –Code will not compile otherwise Example: File commands might cause IOException try { File f = new File(“stuff.txt”); } catch (IOException ex) { … } Opening a file might cause IOExeception if file does not exist, etc. Must be caught

Exception Class Hierarchy Theory vs. Practice –Theory: Any statement that might cause exception should be in try/catch block –Practice: Would need to put almost every statement in try/catch block Any use of object could cause NullPointerException, etc.

Exception Class Hierarchy Compromise: –Only require handling for exceptions that might affect memory external to program Files/Networking: IOException Databases: SQLException Client/Server: ServletException –Problems that cannot be restricted to JVM Design note: –Your exception classes should extend RuntimeException