MODULE 6q - Exceptions

Similar documents
JAVA WRAPPER CLASSES

COSC 123 Computer Creativity. Java Lists and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

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

F I N A L E X A M I N A T I O N

Introduction to Generics in Java 5

Fundamentals of Object Oriented Programming

Overview of Java s Support for Polymorphism

(a) Write the signature (visibility, name, parameters, types) of the method(s) required

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Grouping objects. Main concepts to be covered

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling 2

CS159. Nathan Sprague

Arrays. CSE 142, Summer 2002 Computer Programming 1.

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

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

Highlights of Last Week

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

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

CS 231 Data Structures and Algorithms Fall 2018

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

More sophisticated behaviour

Department of Civil and Environmental Engineering, Spring Semester, ENCE 688R: Final Exam: 2 Hours, Open Book and Open Notes

CS159. Nathan Sprague

Grouping objects Lecture 7

CSE 143 Au03 Midterm 2 Page 1 of 7

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

G51PGP Programming Paradigms. Lecture OO-4 Aggregation

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Introduction to Programming Using Java (98-388)

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

CSC 1214: Object-Oriented Programming

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

Building Java Programs

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

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

CS1083 Week 2: Arrays, ArrayList

CS Programming Language Java. Fall 2004 Sept. 29

CSC Java Programming, Fall Java Data Types and Control Constructs

Generics. IRS W-9 Form

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017

Section 2.2 Your First Program in Java: Printing a Line of Text

1B1a Arrays. Arrays. Indexing. Naming arrays. Why? Using indexing. 1B1a Lecture Slides. Copyright 2003, Graham Roberts 1

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

INSTRUCTIONS TO CANDIDATES

ArrayList. Introduction. java.util.arraylist

Nested Loops. A loop can be nested inside another loop.

JAVA EXAMPLES - SOLVING DEADLOCK

CSE 143 Au04 Midterm 2 Sample Solution Page 1 of 7

Exception Examples. All examples written by Edith Hemaspaandra and modified by Jessica Bayliss

CSE 143 Au03 Midterm 2 Sample Solution Page 1 of 7

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

1 Shyam sir JAVA Notes

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

First Name Last Name ID#

Lesson 26: ArrayList (W08D1)

Midterm Examination (MTA)

Le L c e t c ur u e e 8 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 Collections

CmpSci 187: Programming with Data Structures Spring 2015

Strings and Arrays. Hendrik Speleers

Inf1-OP. Collections. Perdita Stevens, adapting earlier version by Ewan Klein. January 9, School of Informatics

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

COE318 Lecture Notes Week 13 (Nov 28, 2011)

More sophisticated behaviour Lecture 09

1. Find the output of following java program. class MainClass { public static void main (String arg[])

Java for Interfaces and Networks (DT3010, HT11)

Multi-Threaded Programming Design CSCI 201 Principles of Software Development

Methods. Every Java application must have a main method.

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

Questions and Answers. Q.3) asses is not part of Java's collection framework?explanation:

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Java Lectures. Enhancements in Java 1.5

CS 112 Introduction to Programming

2.8. Decision Making: Equality and Relational Operators

Java for Interfaces and Networks (DT3029)

Language Features. 1. The primitive types int, double, and boolean are part of the AP

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Rigidity of arrays. Inf1-OP. ArrayList. ArrayList: Methods. Declaration. Collections

Highlights of Previous Lecture

Object-oriented programming in...

CSCI 1103: File I/O, Scanner, PrintWriter

Getting started with Java

Oracle 1Z0-851 Java Standard Edition 6 Programmer Certified Professional Exam

Grouping objects. The requirement to group objects

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

Full file at

Objects and Iterators

5/23/2015. Core Java Syllabus. VikRam ShaRma

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Object-Oriented Programming with Java

Practice exam for CMSC131-04, Fall 2017

Array. Prepared By - Rifat Shahriyar

Transcription:

MODULE 6q - Exceptions THE TRY-CATCH CONSTRUCT Three different exceptions are referred to in the program below. They are the ArrayIndexOutOfBoundsException which is built-into Java and two others, BadLuckException and BadZeroException, which are declared (as classes) in the program. public class TryCatch { private static int[] a = {12,22,0,19,13,29; private static int p=0; public static void main(string[] args) { while (true) { try { System.out.printf("%d%n", read()); catch(arrayindexoutofboundsexception e) catch 1 { System.out.printf("Finished%n"); break; catch(badluckexception e) catch 2 { System.out.printf("---> %s%n", e.getmessage()); continue; private static int read() throws ArrayIndexOutOfBoundsException, BadLuckException { int n=0; try { n = a[p++]; if (n==0) throw new BadZeroException(); if (n==13) throw new BadLuckException(); catch(badzeroexception e) catch 3 { System.out.printf("---> "); return n; class BadLuckException extends Exception { return "unlucky thirteen"; class BadZeroException extends Exception 1

{ return "Zero"; This yields: 12 22 ---> 0 19 ---> unlucky thirteen 29 Finished TRY IT OUT Key the program in, compile it and run it. It ought to give the results which appear as comments at the end of the program. Next see what happens if, in turn, the catch 1 clause is omitted, the catch 2 clause is omitted and the catch 3 clause heading is changed to catch(badluckexception e) Note also what happens if the throws clause is, in turn, changed to and to throws ArrayIndexOutOfBoundsException throws BadLuckException THE TRY-CATCH-FINALLY CONSTRUCT An adapted version of the above program is given here. It refers to the same three exceptions but includes a try-catch-finally construct. public class TryFinally { private static int[] a = {12,22,0,19,13,29; private static int p=0; private static int totup=0; public static void main(string[] args) { while (true) { try { System.out.printf("%d%n", read()); catch(arrayindexoutofboundsexception e) { System.out.printf("Finished%n"); break; catch(badluckexception e) { System.out.printf("---> %s%n", e.getmessage()); continue; 2

System.out.printf("Read entered %d times%n", totup); private static int read() throws ArrayIndexOutOfBoundsException, BadLuckException { int n=0; try { n = a[p++]; if (n==0) throw new BadZeroException(); if (n==13) throw new BadLuckException(); catch(badzeroexception e) { System.out.printf("---> "); finally { totup++; return n; class BadLuckException extends Exception { return "unlucky thirteen"; class BadZeroException extends Exception { return "Zero"; This yields: 12 22 ---> 0 19 ---> unlucky thirteen 29 Finished Read entered 7 times TRY IT OUT Edit the previous program so that is appears as this new version, compile it and run it. It ought to give the results shown. 3

TRY THIS JIFFY PROGRAM TOO public class HelloC { public static void main(string[] args) throws InterruptedException { System.out.printf("Hello%n"); Thread.sleep(3000L); System.out.printf("World%n"); JAVA COLLECTIONS Java has many facilities for processing collections of items. A simple requirement is an array that will expand and contract as items are are added or removed and the Java class ArrayList in the java.util package achieves this. Class ArrayList implements the interface Collection. Each element is of type Object so it is fully polymorphic. In the following example the ArrayList notes is set up and six items are added to it. One is then removed. The iterator() method in an ArrayList object returns an Iterator object which is assigned to the Iterator variable it. An Iterator enables every item in the collection to be processed. Look up ArrayList and Iterator and try this program out. import java.util.arraylist; import java.util.iterator; public class ArrayListIntro { public static void main(string[] args) { ArrayList notes = new ArrayList(); notes.add("watch"); notes.add("sundial"); notes.add(new Integer(42)); notes.add(new Float(3.142f)); notes.remove("sundial"); Primitive types must be wrapped up to turn them into objects. System.out.printf("The number of notes is %d%n", notes.size()); System.out.printf("The selected entry is %s%n", notes.get(3)); Iterator it = notes.iterator(); while (it.hasnext()) System.out.printf("%s%n", it.next()); This yields: The number of notes is 5 The selected entry is 3.142 4

Watch Clock 42 3.142 Clock Class HashSet also implements the interface Collection. As its name implies a HashSet is a set so repeated elements are not permitted and order is not defined. An attempt to access element three, say, fails. Look up HashSet and try this program out. import java.util.hashset; import java.util.iterator; public class HashSetIntro { public static void main(string[] args) { HashSet notes = new HashSet(); notes.add("watch"); notes.add("sundial"); notes.add(new Integer(42)); notes.add(new Float(3.142f)); notes.remove("sundial"); System.out.printf("The number of notes is %d%n", notes.size()); System.out.printf(notes.get(3));... won t compile Iterator it = notes.iterator(); while (it.hasnext()) System.out.printf("%s%n", it.next()); This yields: The number of notes is 4 Clock 3.142 42 Watch THE HashMap CLASS Class HashMap does not implement the Collection interface but it can be thought of as a close relation. A HashMap is rather like an ArrayList but instead of the elements being indexed by integers they are indexed by keys. Sometimes the term association list is used to describe a HashMap. Notice that the put() method is used instead of an add() method to incorporate a new entry and the put() method takes two arguments. 5

The first is the key and the second is the value. Each is of Object type but in the following example type String is always used for the key. There is no iterator() method in a HashMap object but the keyset() method returns an object which is a set of keys and this DOES have an iterator() method which is duly assigned to the variable it. Look up HashMap and try this program out. import java.util.hashmap; import java.util.iterator; public class HashMapIntro { public static void main(string[] args) { HashMap notes = new HashMap(); notes.put("please", "Watch"); notes.put("come", "Clock"); notes.put("to", "Sundial"); notes.put("our", new Integer(42)); notes.put("christmas", new Float(3.142f)); notes.put("party", "Clock"); notes.remove("to"); System.out.printf("The number of notes is %d%n", notes.size()); System.out.printf("The selected entry is %s%n", notes.get("come")); Iterator it = notes.keyset().iterator(); while (it.hasnext()) System.out.printf("%s%n", notes.get(it.next())); This yields: The number of notes is 5 The selected entry is Clock 42 Clock Clock 3.142 Watch 6