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

Similar documents
OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

I/O. Output. Input. Input ของจาวา จะเป น stream จะอ าน stream ใช คลาส Scanner. standard input. standard output. standard err. command line file.

Defensive Programming. Ric Glassey

COS226 - Spring 2018 Class Meeting # 21 April 23, 2018

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Exceptions Handling Errors using Exceptions

Java Exceptions Version June 2009

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

6.Introducing Classes 9. Exceptions

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

ECE 122. Engineering Problem Solving with Java

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

BBM 102 Introduction to Programming II Spring Exceptions

Internal Classes and Exceptions

BBM 102 Introduction to Programming II Spring 2017

Exceptions. Examples of code which shows the syntax and all that

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

Introductory Programming Exceptions and I/O: sections

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

COSC Exception Handling. Yves Lespérance. Lecture Notes Week 10 Exception Handling

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Download link: Java Exception Handling

Introduction Unit 4: Input, output and exceptions

Programming II (CS300)

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

EXCEPTIONS. Java Programming

Exception Handling CSCI 201 Principles of Software Development

COMP1008 Exceptions. Runtime Error

Object Oriented Programming

Fundamentals of Object Oriented Programming

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

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

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

Programming Languages and Techniques (CIS120)

Object Oriented Programming

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

Programming II (CS300)

Data Structures. 02 Exception Handling

Exception-Handling Overview

Events and Exceptions

Object Oriented Programming Exception Handling

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

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

Exceptions - Example. Exceptions - Example

Exception Handling. Content 25/03/15. Advanced Programming

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

What can go wrong in a Java program while running?

Exceptions and Libraries

Object-Oriented Design. March 2005 Object Oriented Design 1

14. Exception Handling

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Exceptions. CSC207 Winter 2017

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

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


2.6 Error, exception and event handling

Correctness and Robustness

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Errors and Exceptions

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

CS Week 11. Jim Williams, PhD

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

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

Projeto de Software / Programação 3 Tratamento de Exceções. Baldoino Fonseca/Márcio Ribeiro

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

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

ITI Introduction to Computing II

CS 11 java track: lecture 3

16-Dec-10. Consider the following method:

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

CS 3 Introduction to Software Engineering. 3: Exceptions

Assertions and Exceptions Lecture 11 Fall 2005

C16b: Exception Handling

What are Exceptions?

More on Exception Handling

ITI Introduction to Computing II

Java Loose Ends. 11 December 2017 OSU CSE 1

Sri Vidya College of Engineering & Technology Question Bank

IT101. File Input and Output

G Programming Languages - Fall 2012

Exceptions in Java

G51PGP Programming Paradigms. Lecture OO-4 Aggregation

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

23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

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

Chapter 14. Exception Handling and Event Handling ISBN

EXCEPTIONS. Prof. Chris Jermaine

Chapter 13 Exception Handling

CS159. Nathan Sprague

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Transcription:

JAC444 - Lecture 4 Segment 1 - Exception 1

Objectives Upon completion of this lecture, you should be able to: Separate Error-Handling Code from Regular Code Use Exceptions to Handle Exceptional Events Create Your Exceptions 2

Exceptions In this lesson you will be learning about: What is and how to treat an exception in Java How to separate error handling from regular code How to write exception handler Exception class hierarchy How to create your own exception classes 3

What is an exception? Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instruction. Examples: Serious hardware errors, such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds array element. Java solution: The Java method creates an exception object and hands it off to the runtime system. 4

Definitions Throwing an exception It happens when an error occurs the method creates an exception object and hands it off to the runtime system. The exception object The exception object contains information about the exception, including its type and the state of the program when the error occurred. Catching an exception Searching the the call stack until an appropriate exception handler is found. The handler catches the exception. 5

Advantages of Exceptions Separating Error Handling Code from Regular Code Propagating Errors Up the Call Stack Grouping Error Types and Error Differentiation 6

Error Handling Code Problem: Read a file and copy its content into memory readfile ( ) { open the file; determine its size; allocate that much memory; read the file into memory; close the file; 7

Potential Errors What happens if the file can not be opened? What if the length of the file can not be determined? What happens if enough memory can not be allocated? What happens if the read fails? What happens if the file can not be closed? 8

Error Detection Code Solution int readfile ( ) { initialize errorcode = 0; //open the file; if (thefileisopen) { //determine the length of the file; if (gotthefilelength) { //allocate that much memory; if (gotenoughmemory) { //read the file into memory; if (readfailed) { errorcode = -1; else { errorcode = -2; else { errorcode = -3; 9

Java Solution: Exception Handler void readfile() { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; catch (fileopenfailed) { dosomething; catch (sizedeterminationfailed) { dosomething; catch (memoryallocationfailed) { dosomething; catch (readfailed) { dosomething; catch (fileclosefailed) { dosomething; 10

Exception Hierarchy All exceptions that are thrown within a Java program are first-class objects. Leaf class (a class with no subclasses) represents a specific type of exception. Node class (a class with one or more subclasses) represents a group of related exceptions. Node Exception Leaf Exception Leaf Exception 11

ArrayException Example Exception ArrayException InvalidIndexExceptio n NoSuchElementException ElementTypeException 12

Java Exception: Catch / Specify Java language requires that methods either: or Catch Specify an exception (checked exceptions) If an exception is not caught or specified by a method the program does NOT compile 13

Java Solution: Catch or Specify 1 public printstring(...) { try { findstring(...); catch (Exception e) { doerrorprocessing(...); Catch Specify 2 3 public findstring(...) throws Exception { readfile(...); public readfile(...) throws Exception { if (...) throw new Exception(); 14

Catch / Specify Catch A method can catch an exception by providing an exception handler for that type of exception Specify The method could specify that it can throw that exception What are checked exceptions? Checked exceptions are exceptions that are not runtime exceptions and are checked by the compiler 15

Exception Class Hierarchy 16

How to Write an Exception Handler 1. Write the try block It is a block that encloses the statements that might throw an exception 2. Write the catch block(s) It defines the associate with a try block by providing one or more blocks of statements directly after the try block. 3. Write the finally block finally block provides a mechanism that allows your method to clean up after itself 17

The try Block try { Java statements Example: PrintWriter out = null; try { out = new PrintWriter ( new FileWriter( X )); for (int i = 0; i < size; i ++) System.out.println(vector.elementAt(i)); Important note: A try statement must be accompanied by at least one catch block or one finally block. 18

The catch Block(s) One associates exception handlers with a try statement by providing one or more catch blocks directly after the try block: try {... catch (... ) {... catch (... ) {...... The general form of catch statement: catch(throwableclass variablename) { Java statements Catch statement requires a single formal argument. 19

Catching Exception Types Error... Object Throwable Exception RuntimeException try {... catch (Exception e) { System.err.println( Exception caught: + e.getmessage( ) );...... 20

The finally Block For cleanup code use a finally block. try {. PrintWriter out... catch (...) {... finally { if (out!= null) { System.out.println( Closing PrintWriter ); out.close( ); else { System.out.println( PrintWriter not open ); 21

Try, Catch, Finally Blocks public void writelist ( ) { PrintWriter out = null; try { System.out.println( Entering try statement ); out = new PrintWriter(new FileWriter( OutFile.txt )); for (int i = 0; i < size; i++) out.println ( At: + i + = + vector.elementat(i)); catch (ArrayIndexOutOfBoundsException e) { System.err.println( Caught Exception: e.getmessage( )); catch (IOException e) { System.err.println( Caught IOException: + e.getmessage( )); finally { if (out! = null) { System.out.println( Closing PrintWriter ); out.close ( ); else { System.out.println( PrintWriter not open:); 22

Java 8 Try with resources Old exception handling with try and finally static String readfirstlinefromfilewithfinallyblock(string path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readline(); finally { if (br!= null) br.close(); New exception handling Java 8: try with resources static String readfirstlinefromfilewithfinallyblock(string path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readline(); 23

Specifying Exceptions One can specify exceptions in the method definition with the keyword: throws The throws clause is composed of the throws keyword followed by a comma-separated list of all the exceptions thrown by method. Example: public void writelist(...)throws IOException, ArrayIndexOutOfBoundsException{... 24

The Throw Statement The throw statement is used to create an exception object. It requires a single argument as a constructor of an exception object: throw new Exception() Example: The method is taken from a class that implements common stack object. public Object pop( ) throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException( ); obj = objectat(size - 1); setobjectat(size - 1, null); size -- ; return obj; 25

The Throwable Class Errors Java programs should not catch Errors. Exceptions Most programs throw and catch objects that derive from the Exception class. Runtime Exceptions The compiler allows runtime exceptions to go uncaught and unspecified. 26

Conclusion After completion of this lesson you should: 1. Write programs using java.lang.exception package and your defined exceptions 2. Apply the principal: If anything can go wrong, it will. 27