Recitation 4. 2-D arrays. Exceptions. Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] 012012 null Assign.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
1 CS2110–2111 Fall David Gries These slides lead you simply through OO Java, rarely use unexplained terms. Examples, rather than formal definitions,
CS April 2010 Exceptions in Java. Read chapter 10. HUMOR FOR LEXOPHILES (LOVERS OF WORDS): Police were called to a day care; a three-year-old was.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Class Hierarchy (Inheritance)
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
CS1110 Lec November 2010 Exceptions in Java 1 Reading for today: 10. Next lecture: Ch 9.3 No labs this week, no TA office hours Wed-Fri, see consultant.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
CS November 2009 Exceptions in Java. Prof. Gries is lecturing in India for the next 7 days or so. Today’s reading: Ch. 10. Next lecture’s reading:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
CIS 270—Application Development II Chapter 13—Exception Handling.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
CS April 2010 Exceptions in Java. Read chapter 10. HUMOR FOR LEXOPHILES (LOVERS OF WORDS): Police were called to a day care; a three-year-old was.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
CS April 2008 Exceptions in Java. Today’s reading: Ch. 10. Next lecture’s reading: Ch 17. (Most) on-duty consultants now identifiable by stylish.
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Exceptions in the Java programming language J. W. Rider.
Exceptions: When things go wrong
Recitation 2 Exception handling.
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Exceptions & exception handling
Exceptions & exception handling
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Chapter 12 Exception Handling and Text IO Part 1
Presentation transcript:

Recitation 4. 2-D arrays. Exceptions

Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] null Assign value of new-exp to v a6 Assign and refer to elements as usual: v[0]= new Animal(…); … a= v[0].getAge(); (Review: showed this in Lecture 6) v.length is the size of the array

3 Array initializers Instead of int[] c= new int[5]; c[0]= 5; c[1]= 4; c[2]= 7; c[3]= 6; c[4]= 5; Use an array initializer: int[] c= new int[ ] {5, 4, 7, 6, 5}; a0 array initializer: gives values to be in the array initially. Values must have the same type, in this case, int. Length of array is number of values in the list No expression between brackets [ ].

Two-dimensional arrays int[] c= new int[5]; c is a 1-dimensional array int[][] d= new int[5, 8]; You would think this gives an array/table with 5 rows and 8 columns. BUT Java does it differently int[][] d= new int[5][8]; Java does it like this d.length number of rows (5) d[0].length number of columns in row 0 (8) d[1].length number of columns in row 1 (8) d[2][0]= 6; Store 6 in element d[2][0].

5 Java has only 1-dimensional arrays —whose elements can be arrays b a0 null 0101 int[][] b; Declare variable b of type int[][] b= new int[2][] Create a 1-D array of length 2 and store its name in b. Its elements have type int[] (and start as null). In Java, there are really only 1-dimensional arrays, whose elements can be arrays! int[][]

6 Ragged arrays: rows have different lengths b a0 r r r0 r int[][] b; Declare variable b of type int[][] b= new int[2][] Create a 1-D array of length 2 and store its name in b. Its elements have type int[] (and start as null) b[0]= new int[] {17, 13, 19}; Create int array, store its name in b[0]. b[1]= new int[] {28, 95}; Create int array, store its name in b[1].

Division by 0 causes an “Exception to be thrown”. program stops with output: public static void main(String[] args) { int b= 3/0; } Exception in thread "main" java.lang.ArithmeticException: / by zero at C.main(C.java:7) Exceptions The “Exception” that is “thrown” Happened in main, line 7 This is line 7

parseInt throws a NumberFormatException public static void main(String[] args) { … code to store a string in s —expected to be an int int b= Integer.parseInt(s); } /** Parse s as a signed decimal integer and return the integer. If s does not contain a signed decimal integer, throw a NumberFormatException. */ public static int parseInt(String s) parseInt, when it find an error, does not know what caused the error and hence cannot do anything intelligent about it. So it “throws the exception” to the calling method. The normal execution sequence stops! See next slide

parseInt throws a NumberFormatException public static void main(String[] args) { int b= Integer.parseInt(“3.2”); } We see stack of calls that are not completed! Exception in thread "main" java.lang.NumberFormatException: For input string: "3.2" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:458) at java.lang.Integer.parseInt(Integer.java:499) at C.main(C.java:6) Output is: Found error on line 458 called from line 499 called from C.main, line not an int

Exceptions and Errors In Java, there is a class Throwable: “/ by zero” detailMessage getMessage() Throwable() Throwable(String) When some kind of error occurs, an Exception is “thrown” —you’ll see what this means later. An Exception is an instance of class Throwable (or one of its subclasses) Two constructors in class Throwable. Second one stores its String parameter in field detailMessage.

Exceptions and Errors So many different kind of exceptions that we have to organize them. “/ by zero” detailMessage getMessage() Exception RuntimeException ArithmeticException Throwable ExceptionError RuntimeException ArithmeticException Do nothing with these You can "handle" these Throwable() Throwable(String) Exc…() Exc…(..) RunTimeE…() RunTimeE…(…) Arith…E…() Arith…E…(…) Subclass: 2 constructors, no other methods, no fields. Constructor calls superclass constructor

03 public class Ex { 04 public static void main(…) { 05 second(); 06 } public static void second() { 09 third(); 10 } public static void third() { 13 int x= 5 / 0; 14 } 15 } Class: Call Output ArithmeticException: / by zero at Ex.third(Ex.java:13) at Ex.second(Ex.java:9) at Ex.main(Ex.java:5) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(…) at sun.reflect.DelegatingMethodAccessorImpl.invoke(…) at java.lang.reflect.Method.invoke(Method.java:585) AE a0 AE a0 AE a0 Ex.main(); Creating and throwing and Exception

public class Ex { public static void main(…) { second(); } public static void second() { third(); } public static void third() { throw new ArithmeticException("I threw it"); } ArithmeticException: I threw it at Ex.third(Ex.java:14) at Ex.second(Ex.java:9) at Ex.main(Ex.java:5) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(…) at sun.reflect.DelegatingMethodAccessorImpl.invoke(…) at java.lang.reflect.Method.invoke(Method.java:585) AE a0 AE a0 AE a0 Class: Call Output Ex.main(); throw statement

/** An instance is an exception */ public class OurException extends Exception { /** Constructor: an instance with message m*/ public OurException(String m) { super(m); } /** Constructor: an instance with no message */ public OurException() { super(); } How to write an exception class

/** Illustrate exception handling */ public class Ex { public static void main() { second(); } public static void second() { third(); } public static void third() { throw new OurException("mine"); } If a method throws an Exception that is not a subclass of RuntimeException, the method needs a throws clause. Don’t be concerned with this issue. Just write your method and, if Java says it needs a throws clause, put one in Won’t compile. Needs a “throws clause, see next slide

The “throws” clause /** Class to illustrate exception handling */ public class Ex { public static void main() throws OurException { second(); } public static void second() throws OurException { third(); } public static void third() throws OurException { throw new OurException("mine"); } If Java asks for it, insert the throws clause. Otherwise, don’t be concerned with it.

Try statement: catching a thrown exception public class Ex1 { public static void main() throws MyException{ try { second(); } catch (MyException ae) { System.out.println ("Caught MyException: " + ae); } System.out.println ("procedure first is done"); } public static void second() throws MyException { third(); } public static void third() throws MyException { throw new MyException(”yours"); } Execute the try- block. If it finishes without throwing anything, fine. If it throws a MyException object, catch it (execute the catch block); else throw it out further.

/** Input line supposed to contain an int. (whitespace on either side OK). Read line, return the int. If line doesn’t contain int, ask user again */ public static int readLineInt() { String input= readString().trim(); // inv: input contains last input line read; previous // lines did not contain a recognizable integer. while (true) { try { return Integer.valueOf(input).intValue(); } catch (NumberFormatException e) { System.out.println( "Input not int. Must be an int like"); System.out.println("43 or -20. Try again: enter an int:"); input= readString().trim(); } Useful example of catching thrown object readLineInt continues to read a line from keyboard until user types and integer