Java Loose Ends. 11 December 2017 OSU CSE 1

Similar documents
Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

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

Comp 249 Programming Methodology Chapter 9 Exception Handling

Program Correctness and Efficiency. Chapter 2

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Programming II (CS300)

ECE 122. Engineering Problem Solving with Java

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Programming II (CS300)

Exceptions. CSC207 Winter 2017

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

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

Object Oriented Programming. Week 7 Part 1 Exceptions

Chapter 13 Exception Handling

Exception-Handling Overview

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

Chapter 14. Exception Handling and Event Handling

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

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

CS 3 Introduction to Software Engineering. 3: Exceptions

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Internal Classes and Exceptions

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Chapter 14. Exception Handling and Event Handling ISBN

Sri Vidya College of Engineering & Technology Question Bank

Designing Robust Classes

CS112 Lecture: Exceptions and Assertions

Declarations and Access Control SCJP tips

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

Correctness and Robustness

EXCEPTION HANDLING. Summer 2018

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Fundamentals of Object Oriented Programming

Assertions and Exceptions Lecture 11 Fall 2005

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

14. Exception Handling

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Software Construction

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

More on Exception Handling

CS193j, Stanford Handout #25. Exceptions

Exceptions and assertions

More on Exception Handling

COMP1008 Exceptions. Runtime Error

Exceptions, Case Study-Exception handling in C++.

6.Introducing Classes 9. Exceptions

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

Exceptions in Java

BBM 102 Introduction to Programming II Spring Exceptions

CSE 331 Software Design & Implementation

Chapter 14. Exception Handling and Event Handling 异常处理和事件处理. 孟小亮 Xiaoliang MENG, 答疑 ISBN

2IP15 Programming Methods

Exceptions - Example. Exceptions - Example

Defensive Programming. Ric Glassey

Exceptions Handling Errors using Exceptions

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

Chapter 12 Exception Handling

Exceptions. Examples of code which shows the syntax and all that

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

ASSERTIONS AND LOGGING

Data Structures. 02 Exception Handling

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

2.6 Error, exception and event handling

BBM 102 Introduction to Programming II Spring 2017

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

Programming Languages and Techniques (CIS120)

Exceptions. Gunnar Gotshalks EX 1

Defensive Programming

Full file at Chapter 2 - Inheritance and Exception Handling

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java. Xiaoqing Lv 1 1 huihua College Of Hebei Normal University,

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Abstract Classes, Exceptions

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Object Oriented Programming

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

COP4020 Programming Languages. Exception Handling Prof. Robert van Engelen

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

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

Introduction to Software Design

Download link: Java Exception Handling

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Software Design and Analysis for Engineers

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

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

Contents. I Introductory Examples. Topic 06 -Exception Handling

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

Object Oriented Programming

Advanced Flow of Control -- Introduction

Transcription:

Java Loose Ends 11 December 2017 OSU CSE 1

What Else? A few Java issues introduced earlier deserve a more in-depth treatment: Try-Catch and Exceptions Members (static vs. instance) Nested interfaces and classes Access modifiers Final 11 December 2017 OSU CSE 2

Exceptions An exception indicates a problem with an application that entails (in Java) a dramatic change of control flow Vocabulary: Exceptions (and Errors) are thrown by a component implementation caught by a client 11 December 2017 OSU CSE 3

Syntax of Try-Catch In a client, a try-catch statement is used to catch exceptions: try { statements } catch(exceptiontype1 identifier1) { handler for type1 } catch(exceptiontype2 identifier2) { handler for type2 }... 11 December 2017 OSU CSE 4

Execution of Try-Catch If nothing is thrown during execution of the statements in the try block: The try block finishes successfully All catch clauses are ignored (skipped) Execution continues after the try-catch 11 December 2017 OSU CSE 5

Catching an Exception If something is thrown during execution of the statements in the try block: 1. The rest of the code in the try block is skipped 2. The catch clauses are examined top to bottom for the first matching catch 3. If an appropriate catch clause is found: The body of the catch clause is executed The remaining catch clauses are skipped 4. If no such a catch clause is found: The exception is thrown to the outer block, which is either A try block (that potentially handles it, in the same manner) A method body (resulting in it being thrown to its client) 11 December 2017 OSU CSE 6

Use Exceptions in Your Design? Best practice suggests exceptions should be reserved for unexpected situations: Problems external to the application Resource exhaustion Recoverable problems that cannot be handled with checkable preconditions in contracts 11 December 2017 OSU CSE 7

Use Exceptions in Your Design? Best practice suggests exceptions should be reserved for unexpected situations: Problems external to the application Resource exhaustion Recoverable problems that cannot be handled with checkable preconditions in contracts Example: there is a hardware problem with a disk drive. 11 December 2017 OSU CSE 8

Use Exceptions in Your Design? Best practice suggests exceptions should be reserved for unexpected situations: Problems external to the application Resource exhaustion Recoverable problems that cannot be handled with checkable preconditions in contracts Example: the JVM is out of memory for this application. 11 December 2017 OSU CSE 9

Use Exceptions in Your Design? Best practice suggests exceptions should be reserved for unexpected situations: Problems external to the application Resource exhaustion Recoverable problems that cannot be handled with checkable preconditions in contracts Example: a file does not exist because it has been deleted after its existence has already been confirmed. 11 December 2017 OSU CSE 10

Hierarchy of Classes Throwable Error Exception 11 December 2017 OSU CSE 11

Hierarchy of Classes Throwable Error Exception Unrecoverable : hardware, JVM, or application error (e.g., out of memory ) Recoverable : application problem (e.g., file not found ) 11 December 2017 OSU CSE 12

Hierarchy of Error Classes Throwable Error Exception VirtualMachine- Error AssertionError OutOfMemory- Error 11 December 2017 OSU CSE 13

Hierarchy of Error Classes Throwable Error Exception VirtualMachine- Error OutOfMemory- Error AssertionError This is thrown by an assert statement when the condition is false: something is wrong with your program. 11 December 2017 OSU CSE 14

Hierarchy of Error Classes Throwable Error Exception VirtualMachine- Error AssertionError OutOfMemory- Error There are many more subclasses of Error! 11 December 2017 OSU CSE 15

Hierarchy of Exception Classes Throwable Error Exception VirtualMachine- Error AssertionError Runtime- Exception IOException OutOfMemory- Error NullPointer- Exception IndexOutOf- BoundsException Arithmetic- Exception 11 December 2017 OSU CSE 16

Hierarchy of Exception Classes Throwable Error There are many more subclasses of Exception, RuntimeException, and VirtualMachine- Error AssertionError IOException! Exception Runtime- Exception IOException OutOfMemory- Error NullPointer- Exception IndexOutOf- BoundsException Arithmetic- Exception 11 December 2017 OSU CSE 17

Hierarchy of Exception Classes Throwable Error With RuntimeException and its subclasses, something is wrong with VirtualMachine- Error AssertionError your program. Exception Runtime- Exception IOException OutOfMemory- Error NullPointer- Exception IndexOutOf- BoundsException Arithmetic- Exception 11 December 2017 OSU CSE 18

Unchecked vs. Checked Unchecked exceptions are: Error and its subclasses RuntimeException and its subclasses The rest are checked exceptions Checked means that the compiler checks that a method whose body contains a statement that might throw the exception either catches it, or explicitly propagates it up the call chain by declaring that it also throws the exception 11 December 2017 OSU CSE 19

Unchecked vs. Checked Throwable Error Exception VirtualMachine- Error AssertionError Runtime- Exception IOException OutOfMemory- Error NullPointer- Exception IndexOutOf- BoundsException Arithmetic- Exception 11 December 2017 OSU CSE 20

Members A class may have different kinds of members: Variables/fields/data members Constructors Methods Nested classes All except constructors may be either static members or instance members 11 December 2017 OSU CSE 21

Members A class may have different kinds of members: Variables/fields/data members Constructors Methods Nested classes Static methods and instance methods have already been discussed... All except constructors may be either static members or instance members 11 December 2017 OSU CSE 22

Members A class may have different kinds of members: Variables/fields/data members Constructors Methods Nested classes Static members of a class are also called class members, for reasons that will presently become clear. All except constructors may be either static members or instance members 11 December 2017 OSU CSE 23

Static vs. Instance Variables At run-time, a Java program has separate representations for: All static variables for each class C All instance variables for each instance of C, i.e., for each object with dynamic type C Bytecode for C constructors, methods, and nested classes is part of the run-time representation of class C 11 December 2017 OSU CSE 24

Example Class C public class C implements cinterface { private static String svar; private int ivar; public C(String s, int i) { C.sVar = s; this.ivar = i; } public static void smethod(...) {...} public void imethod(...) {...} }... cinterface x1 = new C("foo", 1); cinterface x2 = new C("bar", 2); 11 December 2017 OSU CSE 25

Example Class C public class C implements cinterface { private static String svar; private int ivar; public C(String s, int i) { C.sVar = s; this.ivar = i; } public static void smethod(...) {...} public void imethod(...) {...} }... cinterface x1 = new C("foo", 1); cinterface x2 = new C("bar", 2); The relevant info for upcoming run-time pictures is the part shown in red. 11 December 2017 OSU CSE 26

Run-Time Picture "bar" instanceof instanceof 1 2 11 December 2017 OSU CSE 27

Run-Time Picture There is a run-time representation of each class that holds all its static variables. instanceof "bar" instanceof 1 2 11 December 2017 OSU CSE 28

Run-Time Picture Type erasure: the picture would be the same even if C were generic, say C<T>, and x1 and x2 had different instanceof T. "bar" instanceof 1 2 11 December 2017 OSU CSE 29

Run-Time Picture Surprise! This means that even if C were generic, there would still be only one copy of svar. instanceof "bar" instanceof 1 2 11 December 2017 OSU CSE 30

Run-Time Picture There is a run-time representation of each instance that holds all its instance variables. instanceof "bar" instanceof 1 2 11 December 2017 OSU CSE 31

Run-Time Picture Each instance knows its dynamic type at run-time. "bar" instanceof instanceof 1 2 11 December 2017 OSU CSE 32

Static Initialization Blocks To initialize static variables in a class, you may write a static initialization block that looks like this: static { } // Code to initialize static variables This code is automatically executed when the class is loaded, i.e., once at the very beginning of program execution 11 December 2017 OSU CSE 33

Nested Interfaces An interface may be nested within another interface Example (from OSU CSE components) Map.Pair<K,V> Example (from Java libraries) Map.Entry<K,V> 11 December 2017 OSU CSE 34

Nested Classes A class that is nested as a member of another class may be: A static nested class An instance nested class, which is called an inner class 11 December 2017 OSU CSE 35

Static Nested Class A static nested class does not have access to instance members of its enclosing class Effectively, it s a top-level class declared inside another class since it logically belongs Example (from OSU CSE components): MapSecondary.SimplePair<K,V> Example (from Java libraries): AbstractMap.SimpleEntry<K,V> 11 December 2017 OSU CSE 36

Inner Class Each instance of an inner class belongs to an instance of its enclosing class Has access to generic parameters, variables, methods, etc., of its enclosing instance Examples (from OSU CSE components): Stack2.Node Stack2.Stack2Iterator 11 December 2017 OSU CSE 37

Run-Time Picture 6 18 data data this 2 next next 11 December 2017 OSU CSE 38

Run-Time Picture 6 18 data data this 2 next next These two instances of Node belong to the Stack2 instance that created them. 11 December 2017 OSU CSE 39

Access Modifiers There are four access modifiers in Java. In decreasing order of visibility (but not presented in this order on the following slides), they are: public protected default ( package private ) private 11 December 2017 OSU CSE 40

Access Modifiers There are four access private modifiers apply to in top-level Java. In decreasing order of units, visibility i.e., interfaces (but not and classes; interface presented in this order on the following slides), they are: public protected default ( package private ) private Only public and package members must all be public (which is also the default); class members can be any of the four. 11 December 2017 OSU CSE 41

public A top-level unit declared public is accessible from anywhere So long as it is in scope, e.g., via import, which henceforth goes without saying A member declared public is accessible from anywhere So long as the top-level unit it s in is also accessible, which henceforth goes without saying 11 December 2017 OSU CSE 42

Default ( Package Private ) A top-level unit declared without any access modifier is accessible from anywhere within the same package The default is also called package private accessibility (though probably it should be called package public ) A class member declared without any access modifier is accessible from anywhere within the same package 11 December 2017 OSU CSE 43

This offers little protection against unintended access, because anyone can declare their class to be in a given package (e.g., pkg) simply by adding this as its first line: Default ( Package Private ) A top-level unit declared without any access modifier is accessible from anywhere within the same package package pkg; The default is also called package private accessibility (though probably it should be called package public ) A class member declared without any access modifier is accessible from anywhere within the same package 11 December 2017 OSU CSE 44

Default ( Package Private ) A top-level unit declared without any access modifier is accessible from anywhere within the same package Recall: an interface member declared without any access modifier The default is also called package private accessibility (though probably is public it should be called package public ) A class member declared without any access modifier is accessible from anywhere within the same package 11 December 2017 OSU CSE 45

protected A class member declared protected is accessible from within any subclass, and from anywhere in the same package Example: the JUnit test fixture pattern in which there is a protected method wrapping each constructor of the UUT (which is meant to be overridden in a subclass specific to that UUT) 11 December 2017 OSU CSE 46

protected A class member declared protected is accessible from within any subclass, and from anywhere in the same package Example: the JUnit test fixture pattern in which there is a protected method wrapping each constructor of the UUT (which is meant to be overridden in a subclass specific to that UUT) So, like the default, this offers little protection against unintended access (despite its optimistic name). 11 December 2017 OSU CSE 47

private A class member declared private is accessible only from within the class containing the private member Best practice is to make all static and instance variables private, and to offer public methods with which clients may indirectly manipulate their values An exception: constants, which are normally public static final variables 11 December 2017 OSU CSE 48

The Many Meanings of Final A class declared final may not be extended A method declared final may not be overridden A variable declared final may not be modified once it is given a value Which is why it is often called a constant 11 December 2017 OSU CSE 49

The Many Meanings of Final Be careful! For a reference variable: the reference value cannot be modified, but the object value can be modified! A class declared final may not be extended A method declared final may not be overriddenthe Many Meanings of Final A variable declared final may not be modified once it is given a value Which is why it is often called a constant 11 December 2017 OSU CSE 50

Resources The Java Tutorials: Exceptions http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html The Java Tutorials: Understanding Instance and Class Members http://docs.oracle.com/javase/tutorial/java/javaoo/classvars.html The Java Tutorials: Nested Classes http://docs.oracle.com/javase/tutorial/java/javaoo/nested.html The Java Tutorials: Controlling Access to Members of a Class http://docs.oracle.com/javase/tutorial/java/javaoo/accesscontrol.html 11 December 2017 OSU CSE 51