Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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)
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
13 Copyright © 2011, Oracle and/or its affiliates. All rights reserved. Handling Errors.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
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.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
For use of Cleveland State's IST410 Students only 1 Exception.
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.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
11-Jun-15 Exceptions. 2 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.
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.
16-Jun-15 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.
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.
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:
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
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.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Program Errors Syntax errors Logic errors
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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: 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 Exception handling Exception Handles errors
Introduction to Exceptions in Java
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exceptions & exception handling
Exceptions & exception handling
Exception Handling and Reading / Writing Files
Chapter 14 A List ADT.
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
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
Presentation transcript:

Recitation 3 2D Arrays, Exceptions

2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board games (Chess, Checkers) ●Images (rows and columns of pixels) ●...

1D Array Review Animal[] pets= new Animal[3]; 2D Arrays null pets pets.length is 3 pets[0]= new Animal(); pets[0].walk(); Why is the following illegal? pets[1] = new Object();

Java arrays vs Python lists 2D Arrays Java arrays do not change size! b “Cornell” “Ithaca” “Cornell” “Ithaca” String[] b= {“Cornell”, “Ithaca”}; String[] bBig= Arrays.copyOf(b, 4); b= bBig; bBig

Java array initialization 2D Arrays 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}; Note: The length of c is the number of values in the list.

Exercise 1: Looping over an array /** Return index of occurrence number n of * t in b. * Precondition: n >= 1. * Return -1 if not found. */ public static int get(int[] b, int n, int t) {... } get(new int[]{2110, 0, 1, 2110, 2110}, 2, 2110); would return 3 2D Arrays

2D arrays: An array of 1D arrays. 2D Arrays Java only has 1D arrays, whose elements can also be arrays. int[][] b= new int[2][3]; This array has 2 int[] arrays of length 3 each. 0 1 b

2D arrays: An array of 1D arrays. 2D Arrays How many rows in b ? b.length How many columns in row 0? b[0].length How many columns in row 1? b[1].length 0 1 b

2D arrays: An array of 1D arrays. 2D Arrays int[][] b= new int[2][]; The elements of b are of type int[]. null 0 1 b

2D arrays: An array of 1D arrays. 2D Arrays 0 1 b int[][] b= new int[2][]; b[0]= new int[] {0,4,1,3,9,3}; b[1]= new int[] {1110,2110,3110}; b is called a ragged array

Exercise 2: Transpose Matrix 2D Arrays A T [i][j] is A [j][i] AATAT

Exceptions

Exceptions make your code crash Exceptions public static void main(String[] args) { System.out.println(args[0]); } public static void main(String[] args) { System.out.println(8 / 0); } public static void main(String[] args) { System.out.println(null.toString()); }

What could happen without exceptions? Exceptions public static double getAverage(double[] b) { double sum = 0; for (int i = 0; i < b.length; i++) { sum += b[i]; } return sum / b.length; } If b.length is 0, what should be returned? -Infinity -“special” int - Integer.MAX_VALUE? 2110? 0?

“/ by zero” detailMessage Throwable() Throwable(String) getMessage() Throwable Superclass of exceptions: Throwable Exceptions When some sort of exception occurs, an object of class java.lang.Throwable (or one of its subclasses) is created and “thrown” --we explain later what “throw” means. The object has 1. Field to contain an error message 2. Two constructors 3. Function to get the message in the field

Superclass of exceptions: Throwable Exceptions Two subclasses of Throwable exist: Error: For errors from which one can’t recover –don’t “catch” them Exception: For errors from which a program could potentially recover –it’s ok to “catch” them “/ by zero” detailMessage Throwable() Throwable(String) getMessage() Error() Error(String) Throwable Error “/ by zero” detailMessage Throwable() Throwable(String) getMessage() Exception() Exception(String) Throwable Exception

A Throwable instance: ArithmeticException Exceptions “/ by zero” detailMessage There are so many different kinds of exceptions we need to organize them. Throwable ExceptionError RuntimeException ArithmeticException Throwable Exception ArithmeticException RuntimeException

Throwing an exception Exceptions class Ex { static void main(…) { second(); } static void second() { third(); } Static void third() { int c= 5/0; } AE When an exception is thrown, it is thrown to the place of call, which throws it out further to where that method was called. The code that called main will “catch” the exception and print the error message Console: java.lang.AE: / by zero at Ex.third(Ex.java:11) at Ex.second(Ex.java:7) at Ex.main(Ex.java:3) AE AE = ArithmeticException Method call: main(new String[] {});

Decoding the output from an exception Exceptions public static void main(String[] args) { int div= 5/0; } Exception in thread "main" java.lang.ArithmeticException: / by zero at Animal.main(Animal.java:2) Exception that is thrown line number called method message

Try statement: catching a thrown exception try { code (this is the try-block) } catch (MyException ae) { code (this is the catch-block) } S; (code following the try statement) To execute the try statement: Execute the try-block. If it finishes without throwing an exception, fine. If the try-block throws a MyException object, catch it (execute the catch block); else throw it out further. If the exception was caught, execution proceeds to the code S following the try-statement. ae is like a parameter. When the catch-block catches a thrown object, ae contains the object

throw keyword: Forcing a crash Exceptions Why might I want to crash the application? class Integer { /** Parse s as a signed decimal integer. * Throw a * NumberFormatException if not possible */ public static int parseInt(String s){... } parseInt(“42”) -> 42 parseInt(“Sid”) -> ??? if (can’t convert to int){ throw new NumberFormatException(); }

Demo 1: Read an Integer ●Ask the user to input an int ●Try to convert user input to an int ●If an exception is thrown, catch it and ask for more input

Exercise 3: Illegal Arguments Create class Person with two fields, name and age. Throw an IllegalArgumentException instead of having preconditions when given a null name or a non- positive age. Exceptions

How to write an exception class /** 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(); } Exceptions

throws clause Exceptions public static void second() { … String line= kyboard.readLine(); … } Exceptions Unhandled exception type IOException You may get an error message like the yellow one above. In that case, insert a throws clause as shown below. public static void second() throws IOException { … String line= kyboard.readLine(); }

throws clause for checked exceptions Exceptions If you’re interested in the “controversy”, /** Class to illustrate exception handling */ public class Ex { public static void main() { try { second(); } catch (OurException e) {} } public static void second() throws OurException { third(); } public static void third() throws OurException { throw new OurException("mine"); } Exceptions

Demo 2: Pythagorean Solver ●Given a and b: solve for c in a 2 + b 2 = c 2 ●Reads in input from keyboard ●Handles any exceptions Exceptions

Key takeaways 1.Java arrays do not extend! 2.A 2D array is just a 1D array of 1D arrays. 3.Thrown exceptions bubble up the call stack until they are handled by a try- catch block. In the system, the call of method main is in a try-catch statement, and its catch block prints out information about the thrown exception. Alt-Text: I'm trying to build character but Eclipse is really confusing.