Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 5.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Arrays.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1. 2 Examples for Exception?... An exception is an abnormal condition that arises in a code sequence at run time (Run time error). In other computer languages.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration.
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.
CS0007: Introduction to Computer Programming Introduction to Arrays.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
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.
Java Unit 9: Arrays Declaring and Processing Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Object Oriented Programming
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
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.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
JavaScript and Ajax (Control Structures) Week 4 Web site:
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Information and Computer Sciences University of Hawaii, Manoa
Exceptions In this lecture:
Exceptions, Interfaces & Generics
Why exception handling in C++?
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.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 5

Rina Overview Arrays Exceptions

Rina Arrays An array is a data structure consisting of a numbered list of items. All the items are of the same type. Types of elements in an array can be: primitive type object references An array contains a number of variables. An empty array is an array with number of variables equal to zero.

Rina Indexing The variables contained in an array have no names. They are referenced by array access expressions called index that uses nonnegative integer values. The array variable itself called element of the array.

Rina Array length The number of elements in the array is called the length of the array. The array with n elements is called n length array. The element of the array are referenced using integer indices from 0 to n-1. Example:

Rina Declaring arrays There are two different methods for declaring arrays. Syntax: type Array_name[]; type[] Array_name; The difference is the place of the brackets.

Rina Arrays type Types of an array can be: primitive type objects Examples int grades[]; // array of integers int[] grades; String names[]; // array of strings String[] names;

Rina Arrays type double average[]; // array of doubles double[] average; The advantage of the second method is when several arrays of the same type have to be declared. Example int[] array1,array2,array3;

Rina Creating arrays After the declaration of an array variable the array object can be created. Java arrays are objects. This has several consequences: arrays are created using the new operator no variable can ever hold an array - a variable can only refer to an array

Rina Creating arrays (cont) Syntax: Array_name = new type[size]; Size is an integer that represents the number of elements the array holds (the length of the array). Index of first array element is 0. Index of the last array element is size-1.

Rina Creating arrays (cont) Example: int intArray[]; intArray=new int[10]; Once array has been created you can’t change it’s size. The constant called length holds the size of the array. Syntax: arrayName.length The constant intArray.length contains the value 10.

Rina Creating arrays (cont) In Java, a newly created array is always filled with a known, default value: zero for numbers false for boolean the character with Unicode number zero for char ‘\0’ null for objects

Rina Example int my[]; int my= new int[5]; my holds a reference to an array of 5 integers with default values equal to zero. An array object also contains my.length, which holds the number of items in the array.

Rina Example int my[]; int my= new int[5];

Rina Declaration Declaration and creation of the array can be done together. Syntax: type[] Array_name = new type[size]; Example int [] grades = new int[10];

Rina Array initialization Another way to create an array is to explicitly define the array elements, separated by commas within parentheses. int[] grades = { 90, 78, 80, 95, 89, 80, 69, 93}; String capitals[] = {“London”,“Berlin”, “Jerusalem”}; In this last example: array of String objects was declared and created the array contains 3 elements The explicit definition of an array is also called initialization of the array.

Rina Manipulating arrays Array elements are accessed by specifying the name of the array and it’s place. Syntax: ArrayName[index] Example grades[1] In this example we refer to value 78 (which is the second element of the array grades).

Rina Manipulating arrays Array manipulations are done through its elements. for (int i = 0; i < Array_name.length; i++) {... // process Array_name[i] } Example int numArray = new int[10]; for(int j=0; j <numArray.length; j++) numArray[j] = j; or: String capitals[] = {“London”, “Berlin”, “Jerusalem”}; for (int i = 0; i < capitals.length; i++) System.out.println(capitals[i] );

Rina Manipulating arrays Java has automatic bounds checking to make sure that the bounds of the array are not broken. public class ArrayDemo{ public static void main(String[] args) { int[] a={1,2,3}; try { for(int j=0; j<5; j++)System.out.println(a[j]);} catch(ArrayIndexOutOfBoundsException e) { System.out.print(“Invalid array length");} }} problem

Rina Arrays of Objects Type of an array can be object reference. Example String capitals[] = {“London”, “Berlin”, “Jerusalem”}; Each array element holds a reference to the String object.

Rina Arrays as Parameters A reference to an array can be passed to method as parameter. As usual a copy of the reference is passed to method. Changing an array element in the method changes the original one. Array element can be passed as parameter as well.

Rina Example // public class DArray { public static void doubleArray(int[] array) { for(int j=0;j<array.length;j++) array[j]*=2; } } A reference to an array can be a parameter

Rina Example import DArray; public class DArrayTest {public static void main(String[] args) { int[] array={1,2,3,4}; for(int j=0;j<array.length;j++) System.out.print(array[j]+" "); System.out.println("\nAfter doubling :"); DArray.doubleArray(array); for(int j=0;j<array.length;j++) System.out.print(array[j]+" "); } Array element can be passed as parameter A reference to an array can be a parameter

Rina Multidimensional arrays Arrays can have several dimensions and called multidimensional arrays. Multidimensional arrays created by declaring arrays of arrays. Brackets are represent each dimension in the array. Syntax: type Array_name[]…[] = new type[size]…[size]; Example: double cube[][][]=new double[5][5][5]; int multiArray[][] = new int[10][8];

Rina Two-dimensional arrays Two-dimensional array has values in two dimensions, often called rows and columns. A two-dimensional array can be created as a list of arrays, one for each row in the array. Example int[][] A = { { 1, 0, 12, 11 }, { 7, -3, 2, 5 }, { -5, -2, 2, 9 } };

Rina Two-dimensional arrays Access to an array element is made by specifying the name of the array and index of each dimension. Example: int A=new int[5][6]; A[1][3]=2; The multidimensional array is represented as array of references to array objects. The notation int[2][3] can then be taken to describe a grid of integers with 2rows and 3 columns.

Rina Example int[] my={{56, 3, -4}, {4, 5, 63}}; my holds a reference to an array of 2 elements Each element is a reference to an array of 3 int

Rina Two-dimensional arrays Each dimension has its own length constant. The number of element in the i-th row of the array Name can be found in following way: Name[i-1].length int x=my[1].length;// x is 3 Manipulations can be performed with two- dimensional array.

Rina Example public class MDArray { public static void main(String[] args) { int[][] array={{1,2,3},{4,7},{8,9,12}}; for(int row=0;row<array.length;row++) {for(int col=0;col<array[row].length;col++) System.out.print(array[row][col]+" "); System.out.println(); }

Rina Example /** * A matrix of real numbers. */ public class Matrix { // The elements of the matrix private double[][] elements; /** * Constructs a new matrix from a table of values */ public Matrix(double[][] elements) { //... }

Rina Example /** * Returns the number of rows of the matrix. */ public int numberOfRows() { return elements.length; } /** * Returns the number of columns of the matrix. */ public int numberOfColumns() { return elements[0].length; }

Rina Example /** * Returns the matrix resulting from multiplying * this matrix with another. IllegalArgumentException If the * dimension of the given matrix is not suitable.*/ public Matrix multiply(Matrix a) { int n = numberOfRows(); int m = numberOfColumns(); int l = a.numberOfColumns(); if (m != a.numberOfRows()) { throw new IllegalArgumentException(); }

Rina Example double[][] result = new double[n][l]; for (int i=0; i<n; i++) { for (int j=0; j<l; j++) { for (int k=0; k<m; k++) { result[i][j] += elements[i][k]*elements[k][j]; } return new Matrix(result); }

Rina Example Matrix a,b,c; a = new Matrix(aElements); b = new Matrix(bElements); c = a.multiply(b); for (int i=0; i<c.numberOfRows(); i++) { for (int j=0; j<c.numberOfColumns(); j++) { System.out.print(c.getElement(i,j)+” ”); } System.out.println(); }

Rina Exceptions Run-time errors are an eventuality that all programs may face: – coding errors – erroneous inputs Java provides a sophisticated mechanism called exceptions: – means of communicating run-time errors – means of user-code dealing with such errors

Rina Well written programs Well written programs can minimise the occurrence of run-time errors but: – Users are particularly good at finding new ways to break systems (extraordinary inputs) What do we mean by well written programs? Checking all potential errors before each operation. But it is wasteful, painstaking, obscure and error prone itself.

Rina Exceptions When a program violates the semantic constraints of the Java programming language JVM signals this error to the program as an exception. The word "exception" is meant to be more general than "error." It includes any circumstance that disturb the normal flow of control of the program. Exception defines erroneous or not in control flow.

Rina Exceptions Java provides a method for dealing with possible errors that can occur while a program is running. The method is referred to as exception- handling. An exceptional occurrence in the execution of a program – disrupts the normal flow of execution – can be caught and dealt with by the program

Rina Exception examples Some examples Trying to divide an integer by zero. An error occurs in loading or linking part of the program. Trying to read a file that is inaccessible or doesn’t exist. A ccessing outside an array's bounds.

Rina Other languages Some programming languages and their implementations react to such errors by peremptorily terminating the program. Other programming languages allow an implementation to react in an arbitrary or unpredictable way. A crashed program will often crash the entire system and freeze the computer until it is restarted.

Rina Exceptions Java specifies that an exception will be thrown when semantic constraints are violated. Java will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer. When this happens the program is in danger of crashing.

Rina Exceptions The crash can be avoided if the exception is caught and handled in some way. Having a program crash simply means that it terminates abnormally and prematurely. The Java interpreter catches any exceptions that are not caught by the program. The interpreter responds by terminating the program.

Rina Example public class ArrayDemo{ public static void main(String[] args) { int[] a={1,2,3}; try { for(int j=0; j<5; j++)System.out.println(a[j]);} catch(ArrayIndexOutOfBoundsException e) { System.out.print(“Invalid array length");} }

Rina Exception hierarchy example Often exceptions fall into categories or groups. Example of Array exceptions: Exception RuntimeException IlligalArgumentException NegativeArraySizeException ArrayIndexOutOfBoundsException

Rina Exception types Exceptions are an object ( instances of a class derived from java.lang.Throwable) ArrayIndexOutOfBoundsException e This object can contain information (in its instance variables) from the point where the exception occurred to the point where it is caught and handled. This information typically includes an error message describing what happened to cause the exception, but it could also include other data and methods. System.out.print(“Invalid array length");

Rina Example /** * Constructs a new Rectangle. width The new width. height The new height. IllegalArgumentException if the given width * and heights have illegal value. */ public Rectangle(int width, int height) { if(width<0 || height<0) { throw new IllegalArgumentException(“Rectangle must have positive width and heights!”);} this.width=width; this.height=height; } Error message

Rina Throw keyword throw someThrowableObject; The keyword throw causes a number of relatively magical things to happen. –First an object that represents the error condition is created (usually using new keyword). –The resulting reference is given to throw. –The regular flow of the program stops. –The object is returned from the method, even though that object type isn’t normally what the method is designed to return.

Rina Example class RectangleProblem{ public static void main(String[] args) { //… Rectangle r=new Rectangle(-3,5); int p=r.perimeter(); System.out.println(“Perimeter is “+p); //… } Width should be positive Method crashes

Rina Example class RectangleProblem{ public static void main(String[] args) { //… Rectangle r=new Rectangle(-3,5); int p=r.perimeter(); System.out.println(“Perimeter is “+p); //… } Width should be positive public Rectangle(int width, int height) { if(width<0 || height<0) { throw new IllegalArgumentException (“Rectangle must have positive width and heights!”);} this.width=width; this.height=height;} width = -3 Method crashes

Rina Declaring for Exceptions Before you can catch an exception, some Java code somewhere must throw one. A method can declare exceptions it may throw. The declaration for exceptions a method can throw is done using the throws keyword. The user of the method is warned against possible exceptions this method can throw.

Rina Declaring Exceptions Using ‘throws’ public void setTime(int hour, int minute, int second) throws IllegalArgumentException { if (hour 59 || minute 59 || second 59) { throw new IllegalArgumentException(“Invalid time”); } this.hour = hour; //... }

Rina The try.. catch block If inside a method or another method within this method an exception is thrown that method will exit in the process of throwing. If you don’t want a throw to exit the method, you can set up a special block within that method to capture the exception. This is called the try/catch block. Syntax: try { // code statements } catch (ExceptionType e) { // handler statements}

Rina The try.. catch block The idea is to tell the computer to "try" to execute some statements. If try succeeds catch statements are ignored. But if an exception is thrown by any of the statements within the try block, the rest of the statements are skipped and catch block is executed. Each catch clause has an associated exception type. When an exception occurs, processing continues at the first catch clause that matches the exception type.

Rina The try.. catch block With exception handling, you put everything in a try block and capture all the exceptions in one place. try { //some code } catch (ExceptionType1 e1) { // handler code } catch (ExceptionType2 e2) { // handler code } … catch (ExceptionTypeN eN) { // handler code } This means your code is a lot easier to write and easier to read because the goal of the code is not confused with the error checking.

Rina Example public static void main(String[] args) { //… try{ Rectangle r=new Rectangle(-3,5); int p=r.perimeter(); System.out.println(“Perimeter is “+p); //… } catch(NoSuchMethodException nsme) { //…} catch(IllegalArgumentException ia) {System.out.println(“Rectangle must have positive width and heights!”);} } Width should be positive

Rina Exception propagation After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred. The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate exception handler.

Rina Any Questions?