Java Programming Unit 7. Error Handling. Collec7ons

Size: px
Start display at page:

Download "Java Programming Unit 7. Error Handling. Collec7ons"

Transcription

1 Java Programming Unit 7 Error Handling. Collec7ons

2 Run7me errors An excep7on is an run- 7me error that may stop the execu7on of your program. For example: - someone deleted a file that your program reads - The client calls the server, which doesn t respond - You try to use a variable that should point at the instance of the object but was never ini7alized You should (and oten must) add excep%on handling in your Java programs.

3 Stack Trace 1 class TestStackTrace{ 2 TestStackTrace() 3 { 4 dividebyzero(); int dividebyzero() 8 { 9 return 25/0; sta7c void main(string[]args) 13 { 14 new TestStackTrace(); Run this program and you ll see a stack trace output in the system console. java TestStackTrace Excep7on in thread "main" java.lang.arithme7cexcep7on: / by zero at TestStackTrace.divideByZero(TestStackTrace.java:9) at TestStackTrace.<init>(TestStackTrace.java:4) at TestStackTrace.main(TestStackTrace.java:14) Read it from the bogom up.

4 Walkthrough 1 Download the source code from the Lesson 13 and import it into Eclipse Run the TestStackTrace program and observe the stack trace in the Console view Examine the code of the TestStackTrace2, which handles this excep7on. Run this program

5 Try- catch blocks If you a piece of code may give a run- 7me error, in many cases Java forces you to put it in the try- catch block. For example, reading a file may generate an IOExcep7on: try{ filecustomer.read(); catch (IOExcep7on e){ System.out.println("There seems to be a problem with the file customers. "); Checked excep7ons are the ones that you can foresee, but can t fix inside the program. For example if the file with the customer info is corrupted, there is nothing your program can do about it.

6 Excep7ons Hierarchy Throwable Error Excep7on LoveFailedExcep7on IOExcep7on Subclasses of Excep7on are called checked excep7ons and have to be handled in your code. Subclasses of the class Error are fatal errors and are called unchecked excep%ons.

7 Catching Mul7ple Excep7ons public void getcustomers(){ try{ filecustomers.read(); catch(filenotfoundexcep7on e){ System.out.println( Can not find file Customers ); catch(eofexcep7on e1){ System.out.println( Done with file read ); catch(ioexcep7on e2){ System.out.println( Problem reading file + e2.getmessage()); catch (Excep7on e3){ System.out.println( Something went wrong );

8 Java 7: Mul7catch Star7ng form Java 7 you can catch mul7ple excep7ons in one catch block: public void getcustomers(){ try{ filecustomers.read(); catch(filenotfoundexcep7on EOFExcep7on IOExcep7on e){ System.out.println( Problem reading file +e.getmessage()); catch (Excep7on e1){ System.out.println( Something else went wrong );

9 The throws Keyword class CustomerList{ void getallcustomers() throws IOExcep:on{ // Some other code goes here // Don t use try/catch if you are not handling excep7ons // in this method file.read(); public sta7c void main(string[] args){ System.out.println( Customer List ); Propaga:on of Excep:ons If you are not planning to handle excep7ons in a method, declare that this method may throw and excep7on. Now the caller of getallcustomers() will have top handle it. // Some other code goes here try{ // Since getallcustomers()declared an excep7on, // either handle it over here, or re- throw it //(see the throw keyword explana7on below) getallcustomers(); catch(ioexcep7on e){ System.out.println( Customer List is not available );

10 Walkthrough 2 1. Visit the help page for the class FileInputStream. hgp://download.oracle.com/javase/6/docs/api/java/io/fileinputstream.html 2. Browse the help info on various methods of this class and pay agen7on to the Throws sec7on: 3. Visit the help page for the class IOExcep7on. Take a look at its direct known subclasses: hgp://download.oracle.com/javase/6/docs/api/java/io/ioexcep7on.html

11 The finally keyword If there is a piece of code that must be executed regardless of the success or failure of the code in the try block, put it under the clause finally try{ file.read(); //file.close(); don t close files inside try block catch(excep7on e){ e.printstacktrace(); finally{ file.close(); If a code in a try- catch block uses some external resources, i.e. database connec7ons or open files, you need to close them, and finally is the solu7on in Java 6 and older.

12 Java 7: try statement with resources Java 7 introduces the try- with- resources that supports automa7c closing of the resources without the need to use the finally clause. In the below code sample the file stream will be automa7cally closed without finally. InputStream myfileinputstream = null; try (myfileinputstream=new FileInputStream( customers.txt );) { // the code that reads data from customers.txt goes here catch (Excep7on e){ e.printstarktrace(); To see an example of try with automa7c resource management, refer to this blog: hgp://java.dzone.com/ar7cles/java- 7- new- try- resources This works only if the resource implements java.lang.autocloseable or java.io.closeable interface, which declares just one method close(). FileInputStream implements it.

13 The throw keyword class CustomerList{ throws is just for the declara7on, but throw actually throws the object. void getallcustomers() throws Excep7on{ // some other code goes here try{ file.read(); // this line may throw an excep7on catch (IOExcep7on e) { // Log this error here, and re- throw another excep7on throw new Excep:on ("Customer List is not available "+ e.getmessage()); public sta7c void main(string[] args){ System.out.println( Customer List ); try{ // Since the getallcustomers() declares an excep7on, // you have to either handle or re- throw it getallcustomers(); catch(excep7on e){ System.out.println(e.getMessage());

14 Declaring your own excep7ons class TooManyBikesExcep7on extends Excep7on{ TooManyBikesExcep7on (String msgtext){ super(msgtext); class BikeOrder{ sta7c void validateorder(string bikemodel, int quan7ty) throws TooManyBikesExcep7on{ // perform some data valida7on, and if the entered // the quan7ty or model is invalid, do the following: class OrderWindow extends JFrame{ void ac7onperformed(ac7onevent e){ // the user clicked on the Validate Order bugon try{ bikeorder.validateorder( Model- 123, 50); // the next line will be skipped in case of excep7on txtresult.settext( Order is valid ); catch(toomanybikesexcep7on e){ txtresult.settext(e.getmessage()); throw new TooManyBikesExcep7on( Can not ship + quan7ty+ bikes of the model + bikemodels);

15 Adding useful info to Excep7ons class TooManyBikesExcep7on extends Excep7on{ // Declare an applica7on- specific property ShippingErrorInfo shippingerrorinfo; TooManyBikesExcep7on (String msgtext,shippingerrorinfo shippingerrorinfo){ super(msgtext); this.shippingerrorinfo = shippingerrorinfo;

16 Java 7: Final Rethrow Java 7 allows using the final keyword with excep7ons. try{ // some code goes here catch (final Throwable e){ // some excep7on handling code goes here throw e; This is rather confusing feature. Just know that it exists, but don t waste you 7me on trying to use it in your code. If you are s7ll interested in seeing an example of its use, refer to this blog: hgp://alexbtw.livejournal.com/2927.html

17 Arrays Revisited Customer[] cust = new Customer[10]; cust[0] = new Customer("David","Lee ); cust[1] = new Customer("Ringo","Starr ); cust[9] = new Customer("Lucky","Man ); // Now let's give a 15 percent discount to all customers // who spent more than $500 in our online store: for (Customer c: cust){ if (c.gettotalcharges() > 500){ c.setdiscount(15);

18 Java Collec7on Framework Classes located in the packages java.u:l and java.u:l.concurrent are oten called Java collec7ons. ArrayList, Vector, HashMap, Hashtable, Iterator, Proper7es, Collec7ons. Collec7ons store objects no primi7ves allowed

19 Popula7ng an ArrayList ArrayList customers = new ArrayList(); Customer cust1 = new Customer("David","Lee"); customers.add(cust1); Customer cust2 = new Customer("Ringo","Starr"); customers.add(cust2); add() doesn t copy instance of the Customer into the customers collec7on, it just adds the memory address of the Customer being added. You can specify ini7al size of ArrayList by using constructor with the argument: ArrayList customers = new ArrayList(10);

20 Ge{ng objects from an ArrayList The method get() is used to extract a par7cular element (Object) from the ArrayList. You have to cast it to the appropriate type Customer thebestcustomer=(customer) customers.get(1); You are allowed to add objects of different types to the collec7on: ArrayList customers = new ArrayList(); customers.add(new Customer("David","Lee")); Order ord = new Order(123, 500, "IBM"); customers.add(ord); But during run7me without cas7ng you can get IllegaLCastExcep7on int totalelem = customers.size(); for (int i=0; i< totalelem;i++){ Customer currentcust = (Customer) customers.get(i); currentcust.dosomething(); Using generics (we ll learn in next lesson) can do a compile 7me check: ArrayList<Customer> customers = new ArrayList<Customer> (10);

21 Walkthrough 3 (start) 1. Download and import the source code for Lesson 14 into Eclipse 2. Add the following code to the end of the method main() in the class Test: Order ord = new Order(); customers.add(ord); int totalelem = customers.size(); for (int i=0; i< totalelem;i++){ Customer currentcust =(Customer) customers.get(i); 3. Run Test and observe the run7me excep7on 4. Put the breakpoint (right- click Toggle breakpoint) on the line for (int i=0; i< totalelem;i++){ 5. Debug the program. Observe the content of the variable customers. con:nued

22 Walkthrough 3 (end) 6. Modify the class Customer to look like this: public class Customer { String firstname; String lastname; public Customer (String a, String b){ firstname=a; lastname=b; 7. Add the following line to the end of method main() in class Test: System.out.println("The current customer is " + currentcust.lastname); Why the program doesn t compile? 8. Move the prin7ng line inside the for- loop and rung the program. 9. Observe the output on the console and explain it: The current customer is Lee The current customer is Starr Excep7on in thread "main" java.lang.classcastexcep7on: Order cannot be cast to Customer at Test.main(Test.java:23)

23 Hashtable and Hashmap are for key- value pairs Customer cust = new Customer("David", "Lee"); Order ord = new Order(123, 500, "IBM"); Por~olio port = new Por~olio(123); Hashtable data = new Hashtable(); data.put("customer", cust); data.put("order", ord); data.put("por~olio", port); Ge{ng the object by key: Order myorder = (Order) data.get( Order ); Hashtable is synchronized, but Hashmap is not. You ll understand the difference ater learning about threads and concurrent access explained in Lessons 20 and 21. Hashtable is not used very oten. It has beger replacements in the java.concurrent package (see Lesson 21 of textbook).

24 Class Proper7es Class Proper7es is a special case allowing to store key- value pairs of String type Proper7es prop=new Proper7es(); FileInputStream in =null; try{ in = new FileInputStream ("mailman.proper7es"); prop.load(in); catch(excep7on e){ finally{ in.close(); File mailman.proper7es: SmtpServer=mail.xyz.com to=abc@xyz.com cc=mary@xyz.com from=yakov@xyz.com String from = prop.getproperty("from"); String mailserver=prop.getproperty("smtpserver");

25 Enumera7on interface Enumera7on allows traversing its elements sequen7ally, without even knowing size of the collec7on. Obtain the enumera7on of all elements and use the methods hasmoreelements() and nextelement(). ArrayList customers = new ArrayList(); Enumera7on enum = Collec7ons.enumera7on(customers); //returns Enumera7on while(enum.hasmoreelements()){ Customer currentcust = (Customer) enum.nextelement()); currentcust.dosomething(); Hashtable data = new Hashtable(); // Get the keys Enumera7on enumkeys = data.keys(); while(enum.hasmoreelements()){ // Get the elements Enumera7on enumelements = data.elements();

26 Iterator Interface Iterator is a newer class than Enumera7on. Iterator icust = customers.iterator(); while (icust.hasnext()) { System.out.println( icust.next() ); Enumera7on can only read the elements of the collec7on but Iterator can also remove them from collec7on.

27 LinkedList LinkedList is a collec7on that s useful when you oten need to insert/remove elements of the collec7on. Each element contains a reference to the next one (aka node). Inser7on of a new object inside the list comes down to a simple update of two references. public class TestLinkedList { public sta7c void main(string[] args) { LinkedList passengerlist = new LinkedList(); passengerlist.add("alex Smith"); passengerlist.add("mary Lou"); passengerlist.add("sim Monk"); // Get the list iterator and print every element of the list ListIterator iterator = passengerlist.listiterator(); System.out.println(iterator.next()); System.out.println(iterator.next()); System.out.println(iterator.next());

28 Homework Complete the assignments from the Try It sec7ons for Lessons 13 and 14 Addi:onal read: How to select the right collec7on: hgp://javabeans.asia/ar7cles/cheat- sheet- for- selec7ng- maplistset- in- java.html Oracle s tutorial on Excep7ons: hgp://download.oracle.com/javase/tutorial/essen7al/excep7ons/index.html Using Java 7 AutoCloseable interface: hgp:// 7- try- with- resources- explained.html

Java Programming Unit 7. Error Handling. Excep8ons.

Java Programming Unit 7. Error Handling. Excep8ons. Java Programming Unit 7 Error Handling. Excep8ons. Run8me errors An excep8on is an run- 8me error that may stop the execu8on of your program. For example: - someone deleted a file that a program usually

More information

Java Programming Unit 8. Selected Java Collec5ons. Generics.

Java Programming Unit 8. Selected Java Collec5ons. Generics. Java Programming Unit 8 Selected Java Collec5ons. Generics. Java Collec5ons Framework Classes and interfaces from packages java.util and java.util.concurrent are called Java Collec5ons Framework. java.u5l:

More information

Java Programming Unit 9. Serializa3on. Basic Networking.

Java Programming Unit 9. Serializa3on. Basic Networking. Java Programming Unit 9 Serializa3on. Basic Networking. Serializa3on as per Wikipedia Serializa3on is the process of conver3ng a data structure or an object into a sequence of bits to store it in a file

More information

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1 (remedial) Java anastasia.bezerianos@lri.fr Jars Anastasia Bezerianos 1 Disk organiza0on of Packages! Packages are just directories! For example! class3.inheritancerpg is located in! \remedialjava\src\class3\inheritencerpg!

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

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

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 Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

Core Java Contents. Duration: 25 Hours (1 Month)

Core Java Contents. Duration: 25 Hours (1 Month) Duration: 25 Hours (1 Month) Core Java Contents Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing a Java Application at command prompt Java

More information

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

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

Declaring and ini,alizing 2D arrays

Declaring and ini,alizing 2D arrays Declaring and ini,alizing 2D arrays 4 2D Arrays (Savitch, Chapter 7.5) TOPICS Multidimensional Arrays 2D Array Allocation 2D Array Initialization TicTacToe Game // se2ng up a 2D array final int M=3, N=4;

More information

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

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

6.Introducing Classes 9. Exceptions

6.Introducing Classes 9. Exceptions 6.Introducing Classes 9. Exceptions Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning

More information

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

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

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

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,

More information

Checked and Unchecked Exceptions in Java

Checked and Unchecked Exceptions in Java Checked and Unchecked Exceptions in Java Introduction In this article from my free Java 8 course, I will introduce you to Checked and Unchecked Exceptions in Java. Handling exceptions is the process by

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception

More information

16-Dec-10. Consider the following method:

16-Dec-10. Consider the following method: Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************

More information

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

National University. Faculty of Computer Since and Technology Object Oriented Programming National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java Exceptions in Java What is an exception? An exception is an error condition that changes

More information

Exceptions and Libraries

Exceptions and Libraries Exceptions and Libraries RS 9.3, 6.4 Some slides created by Marty Stepp http://www.cs.washington.edu/143/ Edited by Sarah Heckman 1 Exceptions exception: An object representing an error or unusual condition.

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 25 Nov. 8, 2010 ExcepEons and the Java Abstract Stack Machine Announcements Homework 8 (SpellChecker) is due Nov 15th. Midterm 2 is this Friday, November

More information

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; } Objec,ves Inheritance Ø Overriding methods Garbage collec,on Parameter passing in Java Sept 21, 2016 Sprenkle - CSCI209 1 Assignment 2 Review private int onevar; public Assign2(int par) { onevar = par;

More information

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

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

Exception Handling. Run-time Errors. Methods Failure. 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: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

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

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions. Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws By the end of this lecture, you will be able to differentiate between errors, exceptions, and

More information

CS 10: Problem solving via Object Oriented Programming. Lists Part 1

CS 10: Problem solving via Object Oriented Programming. Lists Part 1 CS 10: Problem solving via Object Oriented Programming Lists Part 1 Agenda 1. Defining a List ADT 2. Generics 3. Singly linked list implementaeon 4. ExcepEons 5. Visibility: public vs. private vs. protected

More information

Sri Vidya College of Engineering & Technology Question Bank

Sri Vidya College of Engineering & Technology Question Bank 1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.

More information

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995 Java Introduc)on History of Java Java was originally developed by Sun Microsystems star:ng in 1991 James Gosling Patrick Naughton Chris Warth Ed Frank Mike Sheridan This language was ini:ally called Oak

More information

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

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15 s Computer Science and Engineering College of Engineering The Ohio State University Lecture 15 Throwable Hierarchy extends implements Throwable Serializable Internal problems or resource exhaustion within

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

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

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

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

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003 The University of Melbourne Department of Computer Science and Software Engineering 433-254 Software Design Semester 2, 2003 Answers for Tutorial 7 Week 8 1. What are exceptions and how are they handled

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Encapsula)on, cont d. Polymorphism, Inheritance part 1. COMP 401, Spring 2015 Lecture 7 1/29/2015

Encapsula)on, cont d. Polymorphism, Inheritance part 1. COMP 401, Spring 2015 Lecture 7 1/29/2015 Encapsula)on, cont d. Polymorphism, Inheritance part 1 COMP 401, Spring 2015 Lecture 7 1/29/2015 Encapsula)on In Prac)ce Part 2: Separate Exposed Behavior Define an interface for all exposed behavior In

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

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

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters. CISC-124 20180215 These notes are intended to summarize and clarify some of the topics that have been covered recently in class. The posted code samples also have extensive explanations of the material.

More information

Here is a hierarchy of classes to deal with Input and Output streams.

Here is a hierarchy of classes to deal with Input and Output streams. PART 15 15. Files and I/O 15.1 Reading and Writing Files A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data

More information

C16b: Exception Handling

C16b: Exception Handling CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1 Outline Exceptions Catch and handle exceptions (try/catch)

More information

More on variables, arrays, debugging

More on variables, arrays, debugging More on variables, arrays, debugging zombie[1] zombie[3] Buuuuugs zombie[4] zombie[2] zombie[5] zombie[0] Fundamentals of Computer Science Keith Vertanen Variables revisited Scoping Arrays revisited Overview

More information

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax Tirgul 1 Today s topics: Course s details and guidelines. Java reminders and additions: Packages Inner classes Command Line rguments Primitive and Reference Data Types Guidelines and overview of exercise

More information

method method public class Temperature { public static void main(string[] args) { // your code here } new

method method public class Temperature { public static void main(string[] args) { // your code here } new Methods Defining Classes and Methods (Savitch, Chapter 5) TOPICS Java methods Java objects Static keyword Parameter passing Constructors A method (a.k.a. func2on, procedure, rou2ne) is a piece of code

More information

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

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception

More information

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

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 7 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential

More information

Input-Output and Exception Handling

Input-Output and Exception Handling Software and Programming I Input-Output and Exception Handling Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Reading and writing text files Exceptions The try block catch and finally

More information

More on collec)ons and sor)ng

More on collec)ons and sor)ng More on collec)ons and sor)ng CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2013 Java Collec/ons API Overview List (last term), e.g. ArrayList Map (last /me), e.g. HashMap Set

More information

COMP1008 Exceptions. Runtime Error

COMP1008 Exceptions. Runtime Error Runtime Error COMP1008 Exceptions Unexpected error that terminates a program. Undesirable Not detectable by compiler. Caused by: Errors in the program logic. Unexpected failure of services E.g., file server

More information

Lab 2: File Input and Output

Lab 2: File Input and Output Lab 2: File Input and Output This lab introduces how to handle files as both input and output. We re coming back to Tracery (which you implemented in Lab 1) with this assignment but instead of always reading

More information

Exceptions Handling Errors using Exceptions

Exceptions Handling Errors using Exceptions Java Programming in Java Exceptions Handling Errors using Exceptions Exceptions Exception = Exceptional Event Exceptions are: objects, derived from java.lang.throwable. Throwable Objects: Errors (Java

More information

Lists. Chapter 12. Copyright 2012 by Pearson Education, Inc. All rights reserved

Lists. Chapter 12. Copyright 2012 by Pearson Education, Inc. All rights reserved Lists Chapter 12 Contents Specifications for the ADT List Using the ADT List Java Class Library: The Interface List Java Class Library: The Class ArrayList Objectives Describe the ADT list Use the ADT

More information

10/7/15. MediaItem tostring Method. Objec,ves. Using booleans in if statements. Review. Javadoc Guidelines

10/7/15. MediaItem tostring Method. Objec,ves. Using booleans in if statements. Review. Javadoc Guidelines Objec,ves Excep,ons Ø Wrap up Files Streams MediaItem tostring Method public String tostring() { String classname = getclass().tostring(); StringBuilder rep = new StringBuilder(classname); return rep.tostring();

More information

Oracle Corporation

Oracle Corporation 1 2011 Oracle Corporation Making heads and tails of Project Coin, Small language changes in JDK 7 Joseph D. Darcy Presenting with LOGO 2 2011 Oracle Corporation Project Coin is a suite of language and

More information

Java Exceptions Version June 2009

Java Exceptions Version June 2009 Java Exceptions Version June 2009 Motivation Report errors, by delegating error handling to higher levels Callee might not know how to recover from an error Caller of a method can handle error in a more

More information

Homework 1 Simple code genera/on. Luca Della Toffola Compiler Design HS15

Homework 1 Simple code genera/on. Luca Della Toffola Compiler Design HS15 Homework 1 Simple code genera/on Luca Della Toffola Compiler Design HS15 1 Administra1ve issues Has everyone found a team- mate? Mailing- list: cd1@lists.inf.ethz.ch Please subscribe if we forgot you 2

More information

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 Contents 1 Exceptions and How They Work 1 1.1 Update to the Banking Example.............................

More information

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

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Ah Lecture Note 29 Streams and Exceptions We saw back in Lecture Note 9 how to design and implement our own Java classes. An object such as a Student4 object contains related fields such as surname,

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

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

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

Generic programming POLYMORPHISM 10/25/13

Generic programming POLYMORPHISM 10/25/13 POLYMORPHISM Generic programming! Code reuse: an algorithm can be applicable to many objects! Goal is to avoid rewri:ng as much as possible! Example: int sqr(int i, int j) { return i*j; double sqr(double

More information

Java Programming Unit 2. Intro to Object Oriented Programming

Java Programming Unit 2. Intro to Object Oriented Programming Java Programming Unit 2 Intro to Object Oriented Programming Classes, methods, fields Java is an object- oriented language - its constructs to represent objects from the real world. Each Java program has

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (IS120) Lecture 30 April 4, 2016 Exceptions hapter 27 HW7: PennPals hat Due: Tuesday Announcements Simplified Example class { public void foo() {.bar(); "here in foo");

More information

Program Correctness and Efficiency. Chapter 2

Program Correctness and Efficiency. Chapter 2 Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you

More information

Complete Java Contents

Complete Java Contents Complete Java Contents Duration: 60 Hours (2.5 Months) Core Java (Duration: 25 Hours (1 Month)) Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Interfaces - An Instrument interface - Multiple Inheritance

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 March 25, 2013 ExcepDons Announcements HW 08 due tonight at midnight Weirich OH: 1:30 3PM today Midterm 2 is this Friday Towne 100 last names A

More information

Collections Questions

Collections Questions Collections Questions https://www.journaldev.com/1330/java-collections-interview-questions-and-answers https://www.baeldung.com/java-collections-interview-questions https://www.javatpoint.com/java-collections-interview-questions

More information

Input from Files. Buffered Reader

Input from Files. Buffered Reader Input from Files Buffered Reader Input from files is always text. You can convert it to ints using Integer.parseInt() We use BufferedReaders to minimize the number of reads to the file. The Buffer reads

More information

Lecture 4: Exceptions. I/O

Lecture 4: Exceptions. I/O Lecture 4: Exceptions. I/O Outline Access control. Class scope Exceptions I/O public class Malicious { public static void main(string[] args) { maliciousmethod(new CreditCard()); } static void maliciousmethod(creditcard

More information

CSE Compilers. Reminders/ Announcements. Lecture 15: Seman9c Analysis, Part III Michael Ringenburg Winter 2013

CSE Compilers. Reminders/ Announcements. Lecture 15: Seman9c Analysis, Part III Michael Ringenburg Winter 2013 CSE 401 - Compilers Lecture 15: Seman9c Analysis, Part III Michael Ringenburg Winter 2013 Winter 2013 UW CSE 401 (Michael Ringenburg) Reminders/ Announcements Project Part 2 due Wednesday Midterm Friday

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward. Introduction to Computation and Problem Solving Class 25: Error Handling in Java Prof. Steven R. Lerman and Dr. V. Judson Harward Goals In this session we are going to explore better and worse ways to

More information

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the Answers 1) B 2) C 3) A 4) D 5) Non-static members 6) Static members 7) Default 8) abstract 9) Local variables 10) Data type default value 11) Data type default value 12) No 13) No 14) Yes 15) No 16) No

More information

Errors and Exceptions

Errors and Exceptions 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 An exception isn t necessarily your fault trying

More information

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

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions Errors and Exceptions 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 An exception is a problem whose cause is outside

More information

Exceptions - Example. Exceptions - Example

Exceptions - Example. Exceptions - Example - Example //precondition: x >= 0 public void sqrt(double x) double root; if (x < 0.0) //What to do? else //compute the square root of x return root; 1 - Example //precondition: x >= 0 public void sqrt(double

More information

Lecture 19 Programming Exceptions CSE11 Fall 2013

Lecture 19 Programming Exceptions CSE11 Fall 2013 Lecture 19 Programming Exceptions CSE11 Fall 2013 When Things go Wrong We've seen a number of run time errors Array Index out of Bounds e.g., Exception in thread "main" java.lang.arrayindexoutofboundsexception:

More information

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Chapter 11 Handling Exceptions and Events. Chapter Objectives Chapter 11 Handling Exceptions and Events Chapter Objectives Learn what an exception is See how a try/catch block is used to handle exceptions Become aware of the hierarchy of exception classes Learn about

More information

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD This Week 1. Battleship: Milestone 3 a. First impressions matter! b. Comment and style 2. Team Lab: ArrayLists 3. BP2, Milestone 1 next Wednesday

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

JDK 7 (2011.7) knight76.tistory.com Knight76 at gmail.com

JDK 7 (2011.7) knight76.tistory.com Knight76 at gmail.com JDK 7 (2011.7) JDK 7 #2 Project Coin knight76.tistory.com Knight76 at gmail.com 1 Project Coin 2 Project Leader Joseph D. Darcy( ) IDEA 2 27, 2009 3 30, 2009 (open call) 70 jdk 7, Language, The Java programming-language

More information

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff Outline 1 Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables: protected Inheritance and constructors, super The is-a vs. has-a relationship (Inheritance

More information

Exceptions. When do we need exception mechanism? When and why use exceptions? The purpose of exceptions

Exceptions. When do we need exception mechanism? When and why use exceptions? The purpose of exceptions Exceptions When do we need exception mechanism? When and why use exceptions? The purpose of exceptions Exceptions An exception is thrown when there is no reasonable way for the code that discovered the

More information

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception

More information

Exceptions. What exceptional things might our programs run in to?

Exceptions. What exceptional things might our programs run in to? Exceptions What exceptional things might our programs run in to? Exceptions do occur Whenever we deal with programs, we deal with computers and users. Whenever we deal with computers, we know things don

More information

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 Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance? CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look

More information

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

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there

More information

Excep&ons and Threads

Excep&ons and Threads Excep&ons and Threads Excep&ons What do you do when a program encounters an anomalous, unusual event? Try to open a file and it's not there Try to convert a string to an integer and it's not a valid integer

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch

More information

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

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions Exceptions Revised 24-Jan-05 CMPUT 115 - Lecture 4 Department of Computing Science University of Alberta About This Lecture In this lecture we will learn how to use Java Exceptions to handle unusual program

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.2) Exception Handling 1 Outline Throw Throws Finally 2 Throw we have only been catching exceptions that are thrown by the Java run-time system. However, it

More information

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

More information

Murach s Beginning Java with Eclipse

Murach s Beginning Java with Eclipse Murach s Beginning Java with Eclipse Introduction xv Section 1 Get started right Chapter 1 An introduction to Java programming 3 Chapter 2 How to start writing Java code 33 Chapter 3 How to use classes

More information

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 1 Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Hwansoo Han T.A. Jeonghwan Park 41 T.A. Sung-in Hong 42 2 Exception An exception

More information