Programming Language Concepts: Lecture 7

Similar documents
Programming Language Concepts: Lecture 7

Programming Language Concepts: Lecture 5

Programming Language Concepts: Lecture 5

Programming Language Concepts: Lecture 6

Polymorphic (Generic) Programming in Java

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exceptions. CSC207 Winter 2017

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

ECE 122. Engineering Problem Solving with Java

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Contents. I Introductory Examples. Topic 06 -Exception Handling

Exception-Handling Overview

COMP1008 Exceptions. Runtime Error

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Chapter 13 Exception Handling

Fundamentals of Object Oriented Programming

Programming II (CS300)

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Properties of an identifier (and the object it represents) may be set at

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Errors and Exceptions

Object Oriented Programming. Week 7 Part 1 Exceptions

Programming II (CS300)

National University. Faculty of Computer Since and Technology Object Oriented Programming

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability.

The list abstract data type defined a number of operations that all list-like objects ought to implement:

Programming II (CS300)

Object-Oriented Design. March 2005 Object Oriented Design 1

School of Informatics, University of Edinburgh

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java Programming Lecture 7

Java Loose Ends. 11 December 2017 OSU CSE 1

APCS Unit 5 Exam. Assuming all four classes have a default constructor, which of the following statements would result in an error from the compiler?

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Abstract Classes, Exceptions

Programming Language Concepts: Lecture 10

CS 61B Discussion 5: Inheritance II Fall 2014

Exceptions and Libraries

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

Lecture 4. Types, Memory, Exceptions

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

Assertions and Exceptions Lecture 11 Fall 2005

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Programming Language Concepts: Lecture 2

Internal Classes and Exceptions

Program Correctness and Efficiency. Chapter 2

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Programming overview

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

Exceptions. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

2IP15 Programming Methods

Object Oriented Programming

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Super-Classes and sub-classes

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Chapter 12 Exception Handling

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

List ADT. Announcements. The List interface. Implementing the List ADT

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

BBM 102 Introduction to Programming II Spring Exceptions

Full file at Chapter 2 - Inheritance and Exception Handling

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

ITI Introduction to Computing II

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

CS365 Midterm -- Spring 2019

Java Primer. CITS2200 Data Structures and Algorithms. Topic 0

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

6.Introducing Classes 9. Exceptions

Sri Vidya College of Engineering & Technology Question Bank

Programming Language Concepts: Lecture 9

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CS 3 Introduction to Software Engineering. 3: Exceptions

Defensive Programming. Ric Glassey

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

ITI Introduction to Computing II

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

BBM 102 Introduction to Programming II Spring 2017

Introduction to Programming Using Java (98-388)

CMSC 132: Object-Oriented Programming II

Chapter 4 Defining Classes I

More on Exception Handling

C++ Inheritance and Encapsulation

Chapter 17: Nested Classes

Cloning Enums. Cloning and Enums BIU OOP

Object Oriented Programming Exception Handling

More on Exception Handling

Casting. References. References

Exceptions and Design

Transcription:

Programming Language Concepts: Lecture 7 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 7, 09 February 2009

Java generics public class Node<T> { public T data; public Node next; I claimed we need to cast the return value to T in a generic LinkedList public class LinkedList<T>{ private int size; private Node first; public T head(){ T returnval = null; if (first!= null){ returnval = first.data; first = first.next; return (T) returnval; // Cast!! public void insert(t newdata){

Java generics But this works OK! public class Node<T> { public T data; public Node<T> next; public class LinkedList<T>{ private int size; private Node<T> first; public T head(){ T returnval = null; if (first!= null){ returnval = first.data; first = first.next; return returnval; // No cast!! public void insert(t newdata){

Problems with generics So we can declare variables of type Node <T> inside a generic class with parameter T

Problems with generics So we can declare variables of type Node <T> inside a generic class with parameter T but we cannot define generic arrays T[] newarray; // Not allowed!

Problems with generics So we can declare variables of type Node <T> inside a generic class with parameter T but we cannot define generic arrays T[] newarray; // Not allowed! We cannot even have LinkedList<Date>[] newarray; Main issue is that arrays are covariant... S subtype of T means S[] is compatible with T[]

Problems with generics So we can declare variables of type Node <T> inside a generic class with parameter T but we cannot define generic arrays T[] newarray; // Not allowed! We cannot even have LinkedList<Date>[] newarray; Main issue is that arrays are covariant... S subtype of T means S[] is compatible with T[]... while generic types not S subtype of T does not imply LinkedList<S> is compatible with LinkedList<T>

Problems with generics So we can declare variables of type Node <T> inside a generic class with parameter T but we cannot define generic arrays T[] newarray; // Not allowed! We cannot even have LinkedList<Date>[] newarray; Main issue is that arrays are covariant... S subtype of T means S[] is compatible with T[]... while generic types not S subtype of T does not imply LinkedList<S> is compatible with LinkedList<T> This could create run time type errors ETicket[] elecarr = new ETicket[10]; Ticket[] ticketarr = elecarr; // OK ticketarr[5] = new Ticket(); // Not OK!

Problems with generics The real problem is not T[] newarray; // Not allowed!

Problems with generics The real problem is not T[] newarray; // Not allowed! but T[] newarray; // OK newarray = new T[100]; // Cannot create!

Problems with generics The real problem is not but T[] newarray; // Not allowed! T[] newarray; // OK newarray = new T[100]; // Cannot create! An ugly workaround T[] newarray; newarray = (T[]) new Object[100]; that generates a compiler warning but works!

Exception handling Exception unexpected event that disrupts normal execution

Exception handling Exception unexpected event that disrupts normal execution Different levels of severity Divide by zero End of file on read

Exception handling Exception unexpected event that disrupts normal execution Different levels of severity Divide by zero End of file on read Need to recover from exceptions Take corrective action if possible Abort only if no option left

Exception handling Exception unexpected event that disrupts normal execution Different levels of severity Divide by zero End of file on read Need to recover from exceptions Take corrective action if possible Abort only if no option left Identifying the cause of an exception Need to go beyond rudimentary coding in terms of integer return values, as in C Exceptions have types!

Exception handling in Java If an error occurs, an operation throws an exception

Exception handling in Java If an error occurs, an operation throws an exception Information about the exception is encapsulated as an object

Exception handling in Java If an error occurs, an operation throws an exception Information about the exception is encapsulated as an object Program in which the offending operation occurred should catch the exception object...

Exception handling in Java If an error occurs, an operation throws an exception Information about the exception is encapsulated as an object Program in which the offending operation occurred should catch the exception object... and handle it Analyze the object to determine the cause of the error Take corrective action if possible

Exception handling in Java All exceptions are subclasses of Throwable Two subclasses, Error and Exception

Exception handling in Java All exceptions are subclasses of Throwable Two subclasses, Error and Exception Error problems beyond program s control An Error... indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

Exception handling in Java All exceptions are subclasses of Throwable Two subclasses, Error and Exception Error problems beyond program s control An Error... indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. Exception normally caught RunTimeException run time errors reported by JVM: divide-by-zero, array out-of-bounds...

Exception handling in Java try-catch structure to handle exceptions try{ // Code that might generate error catch (ExceptionType1 e){ // Corrective code for ExceptionType1 catch (ExceptionType2 e){ // Corrective code for ExceptionType2

Exception handling in Java try-catch structure to handle exceptions try{ // Code that might generate error catch (ExceptionType1 e){ // Corrective code for ExceptionType1 catch (ExceptionType2 e){ // Corrective code for ExceptionType2 Error in try block generates exception object

Exception handling in Java try-catch structure to handle exceptions try{ // Code that might generate error catch (ExceptionType1 e){ // Corrective code for ExceptionType1 catch (ExceptionType2 e){ // Corrective code for ExceptionType2 Error in try block generates exception object Exception object is sequentially checked against each catch

Exception handling in Java try-catch structure to handle exceptions try{ // Code that might generate error catch (ExceptionType1 e){ // Corrective code for ExceptionType1 catch (ExceptionType2 e){ // Corrective code for ExceptionType2 Error in try block generates exception object Exception object is sequentially checked against each catch What happens if first catch is catch (Throwable e1){

Exception handling in Java If some catch condition matches, appropriate code is executed If no catch matches, abort and propagate exception object up one level, to calling class

Exception handling in Java May need to do some cleanup (deallocate resources etc)

Exception handling in Java May need to do some cleanup (deallocate resources etc) This code may be left undone when an exception occurs

Exception handling in Java May need to do some cleanup (deallocate resources etc) This code may be left undone when an exception occurs Add a block labelled finally try{ catch (ExceptionType1 e){ catch (ExceptionType2 e){ finally{ // Always executed, whether try terminates normally // or exceptionally. Use for cleanup statements.

Customized exceptions Don t want negative values in a LinearList

Customized exceptions Don t want negative values in a LinearList Define a new class extending Exception class NegativeException extends Exception{ private int error_value; // Stores negative value that generated exception public NegativeException(String message, int i){ super(message); // Appeal to superclass error_value = i; // constructor to set message public int report_error_value(){ return error_value;

Customized exceptions Inside LinearList class LinearList{ public add(int i){ if (i < 0){ throw new NegativeException("Negative input",i);

Customized exceptions A program using LinearList should be aware that LinearList.add() can result in such an exception

Customized exceptions A program using LinearList should be aware that LinearList.add() can result in such an exception Exception should be advertized by LinearList class LinearList{ public add(int i) throws NegativeException{

Customized exceptions A program using LinearList should be aware that LinearList.add() can result in such an exception Exception should be advertized by LinearList class LinearList{ public add(int i) throws NegativeException{ Need not advertize exceptions of type Error or RunTimeException

Customized exceptions Using LinearList.add() with customized exception LinearList l = new LinearList(); try{ l.add(i); catch (NegativeException ne){ System.out.print("Negative input supplied was "); System.out.print(ne.report_error_value);

Parameter passing in Java Scalars are passed by value No way to write a function to swap two ints

Parameter passing in Java Scalars are passed by value No way to write a function to swap two ints Objects are passed by reference

Parameter passing in Java Scalars are passed by value No way to write a function to swap two ints Objects are passed by reference How do we swap two objects?

Parameter passing in Java Scalars are passed by value No way to write a function to swap two ints Objects are passed by reference How do we swap two objects? class Myclass{ public void swap(myclass p){ // Swap "this" with p Myclass tmp; tmp = p; p = this; this = tmp; Will not work!

Parameter passing Instead, we must write something like: class Myclass{ public void swap(myclass p){ Myclass tmp = new Myclass(); // Make a new tmp ob // Copy contents of p into tmp // Copy contents of this into p // Copy contents of tmp back into this

Parameter passing Return values? Suppose we add a function to Employee class Employee{ // "accessor" methods public Date get_joindate(){ return joindate;

Parameter passing Return values? Suppose we add a function to Employee class Employee{ // "accessor" methods public Date get_joindate(){ return joindate; Now we write Employee e = new Employee(); Date d = e.get_joindate(); d.advance(100); // e loses 100 days seniority!

Parameter passing Return values? Suppose we add a function to Employee class Employee{ // "accessor" methods public Date get_joindate(){ return joindate; Now we write Employee e = new Employee(); Date d = e.get_joindate(); d.advance(100); // e loses 100 days seniority! Get public access to a private field of Employee

Parameter passing Return values? Suppose we add a function to Employee class Employee{ // "accessor" methods public Date get_joindate(){ return joindate; Now we write Employee e = new Employee(); Date d = e.get_joindate(); d.advance(100); // e loses 100 days seniority! Get public access to a private field of Employee Should make a copy of joindate before returning it

Cloning Object class defines Object clone(object o)

Cloning Object class defines Object clone(object o) Makes a bit-wise copy Nested objects will not be cloned automatically!

Cloning Object class defines Object clone(object o) Makes a bit-wise copy Nested objects will not be cloned automatically! To use clone, must implement Cloneable class Employee implements Cloneable{ Marker interface empty!

Cloning Object class defines Object clone(object o) Makes a bit-wise copy Nested objects will not be cloned automatically! To use clone, must implement Cloneable class Employee implements Cloneable{ Marker interface empty! Inside clone(), expect a check such as Object clone(object o){ if (o instanceof Cloneable){ // go ahead and clone else{ // complain and quit

Packages Java has an organizational unit called package By default, all classes in a directory belong to a package If neither public nor private is specified, visibility is with respect to package

Packages Java has an organizational unit called package By default, all classes in a directory belong to a package If neither public nor private is specified, visibility is with respect to package Can use import to use packages directly or import java.math.bigdecimal import java.math.* All classes in /java/math Note that * is not recursive

Protected protected means visible within subtree Normally, a subclass cannot change visibility of a function

Protected protected means visible within subtree Normally, a subclass cannot change visibility of a function However, protected can be made public

Protected protected means visible within subtree Normally, a subclass cannot change visibility of a function However, protected can be made public clone() is defined as protected