Recitation 3. 2D Arrays, Exceptions

Similar documents
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

Review Session. CS2110 Prelim #1 3/8/15. Primitive types vs classes. Default values. Wrapper Classes (Boxing) Strings are immutable.

C16b: Exception Handling

ITI Introduction to Computing II

ITI Introduction to Computing II

Fundamentals of Object Oriented Programming

More on Exception Handling

Full file at Chapter 2 - Inheritance and Exception Handling

COMP1008 Exceptions. Runtime Error


More on Exception Handling

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

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

BBM 102 Introduction to Programming II Spring Exceptions

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

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

Object Oriented Programming

CSCI 261 Computer Science II

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

For more details on SUN Certifications, visit

Index. Strong versus weak typing. Type: Set of values together with operations on them. Casting among types

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

Tutorial 8 Date: 15/04/2014

Programming II (CS300)

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

Introduction to Software Design

CS159. Nathan Sprague

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

Introductory Programming Exceptions and I/O: sections

Exceptions. CSC207 Winter 2017

Exception Handling. Exception Handling

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

CSC 1214: Object-Oriented Programming

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

ECE 122. Engineering Problem Solving with Java

Object Oriented Programming Exception Handling

Java Errors and Exceptions. Because Murphy s Law never fails

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

BBM 102 Introduction to Programming II Spring 2017

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

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

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

Exceptions - Example. Exceptions - Example

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

Correctness and Robustness

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

Std 12 Lesson-10 Exception Handling in Java ( 1

Programming II (CS300)

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

CS112 Lecture: Exceptions and Assertions

What are Exceptions?

CS159. Nathan Sprague

Exception-Handling Overview

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

Prelim 1. CS 2110, March 15, 2016, 5:30 PM Total Question Name True False. Short Answer

Exception Handling in Java

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

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

Exceptions Handling Errors using Exceptions

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

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

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

UE 2I002 (ex LI230) : éléments de programmation par objets avec Java TD10 - Exceptions

What can go wrong in a Java program while running?

Java Programming Language Mr.Rungrote Phonkam

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

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Object Oriented Programming. Week 7 Part 1 Exceptions

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

Object-Oriented Design. March 2005 Object Oriented Design 1

Sri Vidya College of Engineering & Technology Question Bank

Object Oriented Programming

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

2.6 Error, exception and event handling

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

File I/O and Exceptions

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Programming - 2. Common Errors

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Download link: Java Exception Handling

Module 4 - 异常和断言 一 选择题 :

Chapter 13 Exception Handling

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

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

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Data Structures. 02 Exception Handling

Chapter 12 Exception Handling

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

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

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Transcription:

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)...

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

Java arrays vs Python lists 2D Arrays Java arrays do not change size! b A@xab A@x2 A@xab A@x2 bbig A@x2 Cornell Ithaca String[] b = { Cornell, Ithaca ; String[] bbig = Arrays.copyOf(b, 4); b = bbig; 2 3 Cornell Ithaca

Java array initialization 2D Arrays Instead of int[] c= new int[5]; c[]= 5; c[]= 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.

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

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

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

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

2D arrays: An array of D arrays. 2D Arrays int[][] b = new int[2][]; b[] = new int[] {,4,,3,9,3; b[] = new int[] {,2,3; b is called a ragged array b 2 2 3 2 3 4 5 4 3 9 3

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

Exceptions

Exceptions make your code crash Exceptions public static void main(string[] args) { System.out.println(args[]); public static void main(string[] args) { System.out.println(8 / ); 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 = ; for (int i = ; i < b.length; i++) { sum += b[i]; return sum / b.length; If b.length is, what should be returned? - Infinity - special int: Integer.MAX_VALUE? 2??

Exceptions The superclass of exceptions: Throwable class Throwable: Superclass of Error and Exception Does the crashing Contains the constructors and methods Throwable() Throwable(String) class Error: A very serious problem and should not be handled Example: StackOverflowError class Exception: Reasonable application might want to crash or handle the Exception in some way

A Throwable instance: ArithmeticException Exceptions ArithmeticException@x2 Throwable detailmessage Exception / by zero There are so many exceptions we need to organize them. Throwable RuntimeException Exception Error ArithmeticException RuntimeException ArithmeticException

Exceptions Bubbling up exceptions Exceptions will bubble up the call stack and crash the methods that called it. Method call: first(); Console: Exception in thread main java.lang.arithmeticexception: at Ex.third(Ex.java:) at Ex.second(Ex.java:7) at Ex.first(Ex.java:3) AE AE AE 2 3 4 5 6 7 8 9 2 3 class Ex { void first() { second(); void second() { third(); void third() { int c = 5/; AE = ArithmeticException

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

Try-catch blocks An exception will bubble up the call stack and crash the methods that called it unless it is caught. catch will handle any exceptions of type Exception (and its subclasses) that happened in the try block Console: in error 2 3 4 5 6 7 8 9 2 3 4 5 6 7 8 Exceptions class Ex { void first() { second(); void second() { try { System.out.println( in ); third(); System.out.println( out ); catch (Exception e){ System.out.print( error ); Exception Type void third() { int c = 5/; ArithmeticException!

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

Exercise 3: Illegal Arguments Exceptions 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.

How to write an exception class Exceptions /** 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 for checked exceptions /** 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"); If you re interested in the controversy, http://docs.oracle. com/javase/tutorial/essential/exceptions/runtime.html

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

Exercise: Prelim Review Exceptions Analyze try-catch code to see what values will throw an exception

Key takeaways. Java arrays do not extend! 2. A 2D array is just an array of D arrays. 3. Thrown exceptions bubble up the call stack until they are handled by a trycatch 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. http://xkcd.com/88/