Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

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.
CS102--Object Oriented Programming
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.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Exceptions and Exception Handling Carl Alphonce CSE116.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Object-Oriented PHP (1)
Road Map Introduction to object oriented programming. Classes
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
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.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements If a method is in the same class, you execute those declarations.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
Factory Design Pattern, cont’d COMP 401 Fall 2014 Lecture 13 10/2/2014.
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.
Object Oriented Software Development
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
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.
Chapter 12: Exception Handling
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
Java Programming: Guided Learning with Early Objects
Exceptions Handling Exceptionally Sticky Problems.
Question of the Day  A landscaper plants 5 rows of 4 trees each, but only uses 10 trees. How is this possible?
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.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Session 07 Module 13 - Collections. Collections / Session 7 / 2 of 32 Review  A delegate in C# is used to refer to a method in a safe manner.  To invoke.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Error Handling Tonga Institute of Higher Education.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
CIS 200 Test 01 Review. Built-In Types Properties  Exposed “Variables” or accessible values of an object  Can have access controlled via scope modifiers.
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.
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.
Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.
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.
Data Abstraction: The Walls
Generics, Exceptions and Undo Command
Java Programming Language
CS 326 Programming Languages, Concepts and Implementation
Exceptions 10-Nov-18.
Java Programming Language
Exceptions 10-May-19.
CMSC 202 Exceptions.
Presentation transcript:

Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014

Midterm Curve Clarification about point value for multiple choice section. – Each questions worth 5 points. Each choice essentially graded as a T/F question. – Part 1 worth 15*5 = 75 points Not 45 as written in the exam. Exam Curve: – Raw Score Range: 61 – 127 – Average (StdDev): (15.06) – First normalize your raw score: N = (R – Average) / StdDev

Midterm Curve

Exception Trace Example lec12.exception

General Principle: Be Specific Use an existing exception type. – There are lots. – If semantics of the exception match well, then go ahead and use it. Create your own exception type. – Subclass either RuntimeException or Exception lec11.ex9.v1 – Notice how less specific general exception raised by Scanner transformed into context-specific exception for Playlist. – Also note how error message can be retrieved from exception object. See handling of PlaylistFormatError in main() See reference page for Exception for more. 5

General Principle: Catch Late Exceptions should rise to level where application has enough context to deal with them effectively. – Catching exception just because you can is not always the right thing to do. Pass the buck unless you know what to do. – Look again at lec11.ex9.v1 In particular, note handling of FileNotFoundException – lec11.ex9.v2 Note printStackTrace() method of Exception in Main1 Note differences in how FileNotFoundException handled in Main1 vs. Main2 6

General Principle: Throw Early Validate values as early as possible. – Rather than waiting for exception generated by invalid values sent to other code. Particularly apropos for null values that may later cause a NullPointerException Exception generated is not very specific Almost always have to look higher in the stack trace to see what the real problem is. lec11.ex9.v3 7

Odds and Ends Remember that the scope of a variable is limited to the surrounding block. – Sometimes an issue if you declare a variable inside a try block but then need its value outside of the try block later. Sibling catch blocks can reuse the same variable name for the declared error object. A catch block associated with an exception class cannot precede a catch block associated with a subclass. – Results in unreachable code. try-catch-finally blocks can be nested. Interfaces must declare any checked exceptions thrown by any of its implementations. Finally always runs – Even if you “return” from within a try or catch block – lec11.ex10

Factory Design Pattern When direct construction of an object is complicated or harmful – … or at least undesired – By “direct construction”, I mean by using the new keyword Several different contexts when factory design pattern is appropriate: – Singleton When there should only be one instance of a particular class in the whole system. – Multiton When there should only be one instance of of an object associated with some identifying property – Dynamic subclass binding When the specific subclass of an object can only be determined at the time that it is created – Complex construction When the construction of the object requires complex validation and/or side effects that must be handled. When null should be a valid result When an existing object might need to be provided instead of a new one.

The Basic Factory Pattern Make the constructor private – This prevents direct use of the new keyword for creating new objects outside of the class. Provide static class methods that construct new instances and return them. – These are the “factories” – Return type of the factory method is the same as the class. class FPClass { private FPClass() { // Private constructor } public static FPClass factoryMethod() { return new FPClass(); } FPClass o = FPClass.factoryMethod();

Singleton One Object To Rule Them All When there should only be one instance of a particular class in the whole system at any given time. – Generally the object represents some sort of system-wide resource that may be needed by many objects in different parts of the software. – Modifies basic factory pattern by maintaining a single instance. » Created on demand when first requested Lazy initiation » Stored in a private static variable and retrieved by a static getter Static getter is the factory method lec12.ex1 – Simple logging mechanism. lec12.ex2 – A variant that allows for singleton instance to be one of several subclasses.

Multiton Maintains a single instance of the object with regard to some uniquely identifying characteristic of object. Multiton factory method – Static (as per the general factory pattern) – Provided all info. needed to create a new object if necessary. – Determines if corresponding object already exists. If so, returns the existing object If not, creates the new object and inserts it into a static structure Usually implemented using a “map”

Map and HashMap Map is a collection of key/value pairs – Sometimes called a “dictionary” Java Collections Framework – Interface: Map – Implementation: HashMap – K and V are placeholders for type names K for the type of the key, and V for the type of the value. Must be reference types Basic operations: – Creating a new map Map m = new HashMap () – Inserting a value associated with a key m.put(key, value); – Retrieving a value associated with a key V value = m.get(key); – Checking to see if key already in the map m.containsKey(key); // Returns boolean – Removing a key/value pair from the map m.remove(key)

Multiton Example lec12.ex3 – Student is a class that models students Uniquely identified by PID property – getStudent() is factory method Notice that all info needed to create student is provided. – lookupStudent() is a factory method variant that only retrieves existing objects. Does not create object if it doesn’t exist (but must signal that fact) In example, this is done by returning null What would another option have been? lec12.ex4

Value Types In A Reference Type Context Integer reference type – Map can only work with reference types but the key we want to use is simple integer – Java provides reference type versions of basic value types for these kinds of situations. Integer, Double, Character Automatic “boxing” and “unboxing” – As of Java 1.7, can use value type where reference type is expected and Java will automatically “box” the value. – Similarly, will “unbox” a reference type to the value type when assigning to a value type variable.

Dynamic Subclass Binding Useful when choice needs to be made between several different subclasses – Leaves decision about which subclass to use to the factory method Factory method given any/all information that is relevant to decision and for creating new object if necessary. lec12.ex5

A rose by any other name Some design pattern textbooks / frameworks associate the name “Factory” specifically and only for dynamic subclass binding use case. – Other cases described as separate patterns In my presentation, I’ve grouped all of these use cases under the name “Factory” more generally. – Just something to be aware of if/when you encounter the term in tutorials/documentation/etc.