Session 5: Array, Generic, Exception Handling.

Slides:



Advertisements
Similar presentations
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Advertisements

CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
CS102--Object Oriented Programming
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
For use of Cleveland State's IST410 Students only 1 Exception.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
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 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
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.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
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.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
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.
Object Throwable ErrorException RuntimeException.
Appendix H Exception Handling: A Deeper Look
Chapter 13 Exception Handling
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Introduction to Exceptions in Java
Exceptions, Interfaces & Generics
CS102 – Exceptions David Davenport Latest: May 2015
COMPSCI 230 S Programming Techniques
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Advanced Programming Behnam Hatami Fall 2017.
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.
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
Exceptions & exception handling
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Session 4: More on Polymorphism, Array and Exception Handling.
Exception Handling in Java
Lecture 11 Objectives Learn what an exception is.
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.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
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 10-May-19.
Java Exception Dept. Business Computing University of Winnipeg
Java Basics Exception Handling.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Exceptions and Exception Handling
Presentation transcript:

Session 5: Array, Generic, Exception Handling. Java Training Session 5: Array, Generic, Exception Handling.

Arrays A group of variables containing values that all have the same type Arrays are fixed-length entities In Java, arrays are objects, so they are considered reference types But the elements of an array can be either primitive types or reference types (including arrays)

Arrays (contd.) We access the element of an array using the following syntax nameOfArray [ index ] Here, “index” must be a nonnegative integer “index” can be int, byte, short or char but not long In Java, every array knows its own length. The length information is maintained in a public final int member variable called length.

Declaring and Creating Arrays int c[ ] = new int [12]; Here, ‘c’ is a reference to an integer array ‘c’ is now pointing to an array object holding 12 integers Like other objects arrays are created using “new” and are created in the heap “int c[ ]” represents both the data type and the variable name. Placing number here is a syntax error. int c[12]; // syntax error/compiler error

Declaring and Creating Arrays (contd.) int[ ] c = new int [12]; Here, the data type is more evident i.e. “int[ ]” But does the same work as int c[ ] = new int [12]; Is there any difference between the above two approaches? Yes. See the next slide.

Declaring and Creating Arrays (contd.) int c[ ], x; Here, ‘c’ is a reference to an integer array ‘x’ is just a normal integer variable int[ ] c, x; Here, ‘c’ is a reference to an integer array (same as above) But, now ‘x’ is also a reference to an integer array

Using an Array Initializer We can also use an array initializer to create an array int n[ ] = {10, 20, 30, 40, 50}; The length of the above array is 5 n[0] is initialized to 10, n[1] is initialized to 20, and so on The compiler automatically performs a “new” operation taking the count information from the list and initializes the elements properly.

Arrays of Primitive Types When created by “new”, all the elements are initialized with default values byte, short, char, int, long, float and double are initialized to zero boolean is initialized to false This happens for both member arrays and local arrays

Arrays of Reference Types String str[ ] = new String[3]; Only 3 String references are created Those references are initialized to “null” by default Both for member arrays and local arrays Need to explicitly create and assign actual String objects in the above three positions. str[0] = new String(“Hello”); str[1] = “World”; str[2] = “I” + “ Like” + “ Java”;

Passing Arrays to Methods double temperature[ ] = new double[24]; modifyArray( temperature ); Here, “modifyArray” is declared as void modifyArray( double d[ ] ) Changes made to the elements of ‘d’ inside “modifyArray” is visible and reflected in the original “temperature” array. But inside “modifyArray” if we create a new array using “new” and assign it to ‘d’ then ‘d’ will point to the newly created array and changing its elements will have no effect on “temperature” (see next slide).

Passing Arrays to Methods (contd.) So, we can say that while passing array to methods, changing the elements is visible, but changing the array reference itself is not visible. void modifyArray( double d[ ] ) { d[0] = 1.1; // visible to the caller … } d = new double [ 10 ]; d[0] = 1.1; // not visible to the caller

Multidimensional Arrays Can be termed as array of arrays. int b[ ][ ] = new int[3][4]; Length of first dimension = 3 b.length equals 3 Length of second dimension = 4 b[0].length equals 4 int[ ][ ] b = new int[3][4]; Here, the data type is more evident i.e. “int[ ][ ]”

Multidimensional Arrays (contd.) int b[ ][ ] = { { 1, 2, 3 }, { 4, 5, 6 } }; b.length equals 2 b[0].length and b[1].length equals 3 All these examples represent rectangular two dimensional arrays where every row has same number of columns. Java also supports jagged array where rows can have different number of columns (see next slide).

Multidimensional Arrays (contd.) Example - 1 int b[ ][ ]; b = new int[ 2 ][ ]; b[ 0 ] = new int[ 2 ]; b[ 1 ] = new int[ 3 ]; b[0][2] = 7; // will throw an exception Example – 2 int b[ ][ ] = { { 1, 2 }, { 3, 4, 5 } }; b[0][2] = 8; // will throw an exception In both cases b.length equals 2 b[0].length equals 2 b[1].length equals 3 Array ‘b’ Col 0 Col 1 Col 2 Row 0 Row 1 b[0][2] does not exist!!

Let’s Try!! A very easy one!! Write code for matrix addition and multiplication.

Matrix Addition Output: package array; public class MatrixTest{ public static void main(String[] args) { int matrixA[][] = {{1, 2, 3}, {10, 20, 30}, {40, 50, 60}}; intmatrixB[][] = new int[3][3]; matrixB[0][0] = 0; matrixB[0][1] = 1; matrixB[0][2] = 2; matrixB[1][0] = 0; matrixB[1][1] = 10; matrixB[1][2] = 20; MatixA: 1 2 3 10 20 30 40 50 60 MatixB: 0 1 2 0 10 20 30 40 50 Result: 1 3 5 10 30 50 70 90 110 matrixB[2][0] = 30; matrixB[2][1] = 40; matrixB[2][2] = 50; int[][] matrixResult = new int[3][3]; /* Write rest of the code ... */ }

Using Command-Line Arguments java MyClass arg1arg2 … argN Words after the class name are treated as command-line arguments by “java” “java” creates a separate String object containing each command-line argument, places them in a String array and supplies that array to “main” That’s why we have to have a String array parameter (String args[ ]) in “main”. We do not need a “argc” type parameter (for parameter counting) as we can easily use “args.length” to determine the number of parameters supplied.

Using Command-Line Arguments (contd.) public class MyClass { public static void main ( String args[ ] ) System.out.println( args.length ); for( int i = 0; i < args.length; i++) System.out.println( args[i] ); } Sample Execution – 1 java MyClass Hello World Output: 2 Hello World Sample Execution – 2 java MyClass Hello 2 you 3 you

Generics Some times we may need to implement same algorithm for different types of variable. Consider a Stack or Queue implementation. One may need a stack of Double while other may be need stack of Integer. But the algorithm is same inside. Last In First Out. Writing separate implementations for Integer and double is waste of time.

Generics Solution is generic. Conception is we will create a algorithm related object with what type elements the algorithm will perform on. Ex. ArrayList, VectorList Our discussion will be limited in using generic class in Java Colloection.

Example Output: Length: 3 Element(0): 13 Element(1): 19 List elements: ArrayList<Integer> list = new ArrayList<Integer>(); list.add(13); list.add(17); list.add(19); System.out.println("Length: " + list.size()); System.out.println("Element(0): " + list.get(0)); System.out.println("Element(1): " + list.get(2)); System.out.println("List Elements:"); for (Integer integer : list) { System.out.println(integer); } Output: Length: 3 Element(0): 13 Element(1): 19 List elements: 13 17 19

Example ArrayList<Double>doubleList = new ArrayList<Double>(); doubleList.add(13.12); doubleList.add(17.2); doubleList.add(19.123); doubleList.add(23.12); System.out.println("Length: " + doubleList.size()); System.out.println("Element(0): " + doubleList.get(0)); System.out.println("Element(1): " + doubleList.get(2)); System.out.println("List Elements:"); for (Double d : doubleList) { System.out.println(d); } Output: Length: 4 Element(0): 13.12 Element(1): 19.123 List Elements: 13.12 17.2 19.123 23.12

Generics No wonder generics is one of the very interesting features of java. For more on generics please follow the oracle java tutorial - http://download.oracle.com/javase/tutorial/java/generics/index.html There is a book name Java Generics. You can give it a try.

Exception Handling Say we have an array of size 3. Like String str[] = new String[3]; But we accessed str[4]; then java will throw an exception nameArrayIndexOutOfBoundsException How to handle those?

try { } catch try { String str[] = new String[3]; str[4] = "123"; //will throw exception. System.out.println("This line won't be executed"); System.out.println("This line too"); int b = 100; System.out.println("Value of b: " + b + " but this won't be executed too"); } catch (ArrayIndexOutOfBoundsExceptionaioobe) { System.err.println("Improper access."); }

Exception-Handling Overview Enables programmers to remove error-handling code from the “main line” of the program’s execution Improves program clarity Enhances modifiability Java forces the programmer to be prepared for certain types of problems so that sudden occurrence of such problems do not cause significant damage.

Exception-Handling Overview (contd.) If a single-threaded program does not handle an exception, then it will be terminated immediately. If a multi-threaded program does not handle an exception, then it may not be terminated, but may show unusual behaviors. So, it is better to be prepared for different types of exceptions.

Syntax A single “try” block may be followed by zero or multiple “catch” blocks. If no “catch” block is provided, then a “finally” block must be provided for a “try” block. If no exception is thrown in the “try” block, then all the “catch” blocks are skipped and execution resumes after the last “catch” block. If an exception is thrown inside the “try” block, then execution immediately leaves the “try” block and Java searches for an appropriate “catch” handler capable of handling the exception from top to bottom. The first matching “catch” block is executed. All other “catch” blocks at the same level are skipped. The necessary information about the exception is wrapped inside an exception object and supplied to the corresponding “catch” handler. After all, Java does not do anything without objects. try { // statements that may throw exceptions } catch(ExceptionType1 refName) // statements to process ExceptionType1 catch(ExceptionType2 refName) // statements to process ExceptionType2 … catch(ExceptionTypeNrefName) // statements to process ExceptionTypeN

Some Common Exceptions Exception classes in the Java API ArrayIndexOutOfBoundsException NullPointerException ClassCastException ArithmeticException InputMismatchException FileNotFoundException InterruptedException IOException (package java.io) Exception (package java.lang) And many more. You can also develop your own exception classes.

Throwing an Exception You can throw an exception using the “throw” statement. throw new Exception(); You can only throw an object of a class which is Throwable, i.e. a subclass of the Java API class Throwable. You can also rethrow a caught exception. It will be handled by the next outer level exception handler (if one is present) try { } catch(Exception e) { throw e; }

Using the throws Clause If a method does not want to handle an exception then it must declare that it may throw the exception using the throws clause void methodName( ) throws Exception1, Exception2 That means Java employs a catch or declare strategy in exception-handling If you do not catch a particular exception, you must declare it There is a little deviation from this rule (see the discussion on unchecked exceptions later)

Exception in Constructor If a exception is thrown in constructor then the object is not constructed!!

Let’s Try!! Write a Student class in student package. Student has two fields. Name Marks Throw Exceptions in time of creation of student If the Name is null or empty string with message “Student name can not be empty” If Mark is less then 0 or greater then 100 with message “Invalid marks”

Output Output: Error occured: Student name can not be empty try { Student student = new Student("", 10); System.out.println("This line won't be executed."); System.out.println(student); } catch (Exception ex) { System.err.println("Erroroccured: " + ex.getMessage()); } Student student = new Student("Abcd", 10000); Student student = new Student("Abcd", 97); Output: Error occured: Student name can not be empty [Name: Abcd, 97] Invalid Marks

When to Use Exception Handling Exception handling is designed to process synchronous errors, which occur when a statement executes Out-of-range array indices Arithmetic overflow Division by zero Thread interruption etc.

Java Exception Hierarchy (Partial List) Throwable Exception Error RuntimeException IOException OutOfMemoryError ThreadDeath ClassCastException NullPointerException

Checked vs. Unchecked Exceptions Must be caught (using try … catch) or declared using throws If not handled properly, Java compiler (javac) issues compiler error Example: All classes that inherit from class Exception but not class RuntimeException Unchecked Exceptions May or may not be handled Handling not enforced by the Java compiler All exception types that are direct or indirect subclasses of class RuntimeException ArrayIndexOutOfBoundsException, ArithmeticException etc. Classes that inherit from class Error

Arrangement of catch Blocks catch blocks for a try block must be arranged from specific to general order If we place a superclass exception before a subclass exception then Java compiler (javac) will flag it as an error Consider the following exception inheritance - java.lang.Exception java.io.IOException java.io.EOFException Now, in order to handle exceptions of these types, we have to catch them from most specific to more general case (see next slide)

Arrangement of catch Blocks (contd.) try { // statements that may throw exceptions } catch(EOFException eofe) { catch(Exception e) { // this catch block should be the last catch block catch(IOException ioe) { Invalid ordering of catch blocks try { // statements that may throw exceptions } catch(EOFException eofe) { catch(IOException ioe) { catch(Exception e) { Correct ordering of catch blocks

finally block It is an optional block/clause Must be placed after the last catch block Codes present in this block are always executed whether exception occurs or not inside the try block A finally block will also execute if a try block exits by using a return, break or continue statement Generally used to release system resources like closing files, sockets etc. The finally block will not execute if we use System.exit inside the try block or a catch block that gets executed after an exception occurs

Declaring New Exception Types // File: StackException.java public class StackException extends Exception { public StackException( ) { super( “Stack exception occurred” ); } public StackException( String message ) { super( message );