CSC 212 – Data Structures Lecture 10: More Inheritance & Exceptions.

Slides:



Advertisements
Similar presentations
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Advertisements

Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
Index Exception handling Exception In Java Exception Types
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.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
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:
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
12.1 Exceptions The limitations of traditional methods of exception handling Error conditions are a certainty in programming Programmers make.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
Object Oriented Programming
CIS 270—Application Development II Chapter 13—Exception Handling.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Slides Credit Umair Javed LUMS Web Application Development.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
CSC 212 – Data Structures Lecture 12: Java Review.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
COMP Exception Handling Yi Hong June 10, 2015.
Question of the Day  A landscaper plants 5 rows of 4 trees each, but only uses 10 trees. How is this possible?
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
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.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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.
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.
Question of the Day completes starts  What word completes the 1 st word & starts the 2 nd one: DON???CAR.
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.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
MIT AITI 2003 Lecture14 Exceptions
CSE 116/504 – Intro. To Computer Science for Majors II
Java Programming Language
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
Presentation transcript:

CSC 212 – Data Structures Lecture 10: More Inheritance & Exceptions

Method Inheritance Subclass overloads methods like normal Subclass can also override method  Identical signature, no less restrictive access  Which method called depends on instance Use of super keyword within a method  Usage of super different within constructor  Calls method as defined in superclass  Only used in overriding method definition  Call is super.methodName(…);

Field Inheritance Non-private fields inherited as normal  Private fields accessible through methods in superclass Fields are hidden not overriden  Declare field with same name in subclass  Types do not need to the same  Objects have both field

Accessing Hidden Field Field accessed depends on variable type  Use field that corresponds to type of variable  Superclass methods & variables of superclass type use field defined in superclass  Subclass methods can access field from superclass using super.fieldName  Subclass methods & variables of subclass type use field defined in subclass

Inheritance Review Non-private methods & fields inherited by subclass  As if they were cut-and-pasted into subclass Method called depends on instance type Field used depends on variable type Sorry it is this ugly (There is a good reason for this; if curious ask me outside of class)

Error Handling Goals Best way to handle error that prevents executing as normal?  Must return to where this error can be fixed  Handle error in manner that makes sense for that moment of time  If class is reused, may want to handle error differently  Guarantee error is handled or known by user

Solve Problems with Exceptions ex-cep-tion: n. an instance or case not conforming to the general rule  Proper way to signal error in object-oriented code Java already includes many exceptions  ArrayIndexOutOfBoundsException signals access to nonexistent array entry  NullPointerException generated when using null reference

Exceptions in Java Throw exception when problem detected Handle problem by catching exception In Java, exceptions are actually objects  Must first be instantiated (new)  Can assign exception object’s fields  Then throw the exception instance

Throwing an Exception private float withdrawal(float amt) throws BadRequestException { if (amt < 0) { BadRequestException bre=new BadReqestException(); bre.setRequest(amt); throw bre; } else if (amt > balance) { throw new BadRequestException(amt, balance); } balance -= amt; return balance; }

Handling Exceptions When an exception is thrown, methods can do one of 3 things:  handle the error and continue  handle the exception and throw a new one  ignore the exception Once thrown, exception must be handled or program must end  Want air traffic using computer after it lost a plane?

Catching an Exception Blocks can list multiple catch statements  Exceptions will be caught by first matching catch statement  If no catch matches current exception, exception is thrown on to calling method try-catch blocks do not need to catch all possible exceptions  But uncaught exceptions are passed on

Catching an Exception public void atmWithdrawal(float amt) { try { withdrawal(amt); addToRegister(amt); } catch (BadRequestException bre) { if (bre.getAmount() < 0) { System.err.println(“Trying to get rich?”); } else { System.err.println(“Get a job, deadbeat!”); } } catch (Exception e) { System.out.println(“Caught other exception”); System.err.println(e.toString()); } }

Catching an Exception (2) public void withdrawalWithGun(float amt) throws BadRequestException { callPolice(); addDyePacks(); withdrawal(amt); }

Checked vs. Unchecked Two different flavors of exceptions Checked exceptions MUST be listed in throws clauses  Listing required if thrown in method  Also needed if the method “throws” the exception by ignore it Unchecked exceptions can be thrown anywhere and need not be declared  Used fixing error is impossible

Checked vs. Unchecked Exception Subclasses of Exception (except RuntimeException) are checked exceptions. These represent errors a programmer must fix. Runtime Exception Subclasses of RunTimeException are unchecked exceptions. These represent errors that occur during runtime and may not be able to be fixed.

Tracing With Exceptions public static void dumbExample(int i) { int j = 0; char c = ‘a’ try { System.out.println(“Starting”); if (i == 0) { throw new DumbException(); } System.out.println(“Ending”); } catch (DumbException de) { System.out.println(“Excepting”); } }

Another Tracing Example public static int generatesException() throws TraceException { try { System.out.println(“Starting gE”); throw new TraceException(); System.out.println(“Ending gE”); return 0; } catch (NullPointerException npe) { return 1; } } public static void callsException(boolean callIt) { try { System.out.println(“Starting cE”); if (callIt) { generateException(); } System.out.println(“Ending cE”); } catch (TraceException te) { System.out.println(“Caught te”); } }

public static int generatesException() throws TraceException { try { System.out.println(“Starting gE”); throw new TraceException(); System.out.println(“Ending gE”); return 0; } catch (NullPointerException npe) { return 1; } } public static void callsException(boolean callIt) { try { System.out.println(“Starting cE”); if (callIt) { generateException(); } System.out.println(“Ending cE”); } catch (TraceException te) { System.out.println(“Caught te”); } } public static void masterMethod() { callsException(false); callsException(true); }

Your Turn Get back into groups and do activity

Before Next Lecture… Review week #4 assignment Continue programming assignment #1  It is due 2 weeks from last Friday Start reviewing for Midterm #1  It will be 2 weeks from last Monday Friday’s lecture discusses object hierarchies & generic types  Read Sections of the book