OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

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

Defensive Programming. Ric Glassey

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

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

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

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

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

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

6.Introducing Classes 9. Exceptions

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

Exceptions Handling Errors using Exceptions

What are Exceptions?

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

Introduction Unit 4: Input, output and exceptions

ECE 122. Engineering Problem Solving with Java

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

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

Java Exceptions Version June 2009

CSPP : Introduction to Object-Oriented Programming

Input-Output and Exception Handling

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

Exceptions - Example. Exceptions - Example

EXCEPTIONS. Prof. Chris Jermaine

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

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

Errors and Exceptions

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

COMP1008 Exceptions. Runtime Error

Programming II (CS300)

BBM 102 Introduction to Programming II Spring Exceptions

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

COMP-202 Unit 9: Exceptions

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

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

More on Exception Handling

Exceptions. CSC207 Winter 2017

Programming II (CS300)

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

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

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

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

More on Exception Handling

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

Exception-Handling Overview

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

Fundamentals of Object Oriented Programming

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

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

BBM 102 Introduction to Programming II Spring 2017

2.6 Error, exception and event handling

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

COMP-202 Unit 9: Exceptions

Data Structures. 02 Exception Handling

Special error return Constructors do not have a return value What if method uses the full range of the return type?

EXCEPTIONS. Java Programming

ITI Introduction to Computing II

IT101. File Input and Output

ITI Introduction to Computing II

Introduction to Software Engineering in Java. Exceptions, I/O, and you++

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

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

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Full file at Chapter 2 - Inheritance and Exception Handling

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

Exceptions and Libraries

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

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

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

16-Dec-10. Consider the following method:

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

Abstract Classes, Exceptions

Why Exceptions? (1.1) Exceptions. Why Exceptions? (1.2) Caller vs. Callee. EECS2030 B: Advanced Object Oriented Programming Fall 2018

Exceptions. EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG

C16b: Exception Handling

Object Oriented Software Design

Object Oriented Software Design

Internal Classes and Exceptions

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

14. Exception Handling

17. Handling Runtime Problems

Download link: Java Exception Handling

Main concepts to be covered. Handling errors. Some causes of error situations. Not always programmer error. Defensive programming.


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

MSc/ICY Software Workshop Exception Handling, Assertions Scanner, Patterns File Input/Output

Chapter 14. Exception Handling and Event Handling ISBN

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

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

Introduction to Java Written by John Bell for CS 342, Spring 2018

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

Java file manipulations

EXCEPTION HANDLING. Summer 2018

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

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

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

Transcription:

OBJECT ORIENTED PROGRAMMING Course 6 Loredana STANCIU loredana.stanciu@upt.ro Room B616

Exceptions An event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions When an error occurs within a method exception object throwing an exception The runtime system attempts to find something to handle it call stack

Exceptions Exception handler block of code that can handle the exception The exception handler chosen is said to catch the exception If no exception handle found the program terminates

Exceptions

The Catch or Specify Requirement The code that might throw certain exceptions must be enclosed by: A try statement that catches the exception A method that specifies that it can throw the exception must provide a throws clause Code that fails to honor the Catch or Specify Requirement will not compile.

The Three Kinds of Exceptions 1) the checked exception exceptional conditions that a well-written application should anticipate and recover from Exp: try to open for reading a file but the file does not exist java.io.filenotfoundexce ption catch this exception and notify the user of the mistake

The Three Kinds of Exceptions 2) the error conditions that are external to the application, and that the application usually cannot anticipate or recover from indicated by Error and its subclasses Exp: an application successfully opens a file for input, but is unable to read the file java.io.ioerror

The Three Kinds of Exceptions 3) the runtime exception are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from indicated by RuntimeException and its subclasses Exp: If a logic error causes a null to be passed to the constructor NullPointerException

Catching and Handling Exceptions //Note: This class won't compile by design! import java.io.*; import java.util.list; import java.util.arraylist; public class ListOfNumbers { private List<Integer> list; private static final int SIZE = 10; public ListOfNumbers () { list = new ArrayList<Integer>(SIZE); for (int i = 0; i < SIZE; i++) list.add(new Integer(i));

Catching and Handling Exceptions public void writelist() { PrintWriter out = new PrintWriter( new FileWriter("OutFile.txt")); // (1) for (int i = 0; i < SIZE; i++) out.println("value at: " + i + " = " + list.get(i)); // (2) out.close(); (1) generates an IOException (2) generates an ArrayIndexOutOfBoundsException

The try Block Enclose the code that might throw an exception within a try block try { code } catch and finally blocks... code contains one or more legal lines of code that could throw an exception

The try Block public void writelist() { PrintWriter out = null; try { System.out.println("Entered try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) out.println("value at: " + i + " = " + list.get(i)); catch and finally statements...

The catch Blocks Associate exception handlers with a try block by providing one or more catch blocks directly after the try block No code can be between the end of the try block and the beginning of the first catch block try { } catch (ExceptionType name) { } catch (ExceptionType name) { }

The catch Blocks try { } catch (FileNotFoundException e) { System.err.println("FileNotFoundExcepti on: " + e.getmessage()); throw new SampleException(e); catch (IOException e) { System.err.println("Caught IOException: " + e.getmessage());

The finally Block Always executes when the try block exits Used to put cleanup code Exp: 1) The new FileWriter statement fails and throws an IOException. 2) The list.get(i) statement fails and throws an ArrayIndexOutOfBoundsException. 3) Everything succeeds and the try block exits normally.

The finally Block finally { if (out!= null) { System.out.println("Closing PrintWriter"); out.close(); else { System.out.println("PrintWriter not open");

The finally Block try { out.close(); //Don't do this; it duplicates code. catch (FileNotFoundException e) { System.err.println("Caught: FileNotFoundException: " + e.getmessage()); throw new RuntimeException(e); catch (IOException e) { out.close(); //Don't do this; it duplicates code. System.err.println("Caught IOException: " + e.getmessage());

The finally Block Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to insure that resource is always recovered.

Specifying the Exceptions Thrown by a Method Sometimes, it's appropriate for code to catch exceptions that can occur within it. In other cases, it's better to let a method further up the call stack handle the exception. public void writelist() throws IOException, ArrayIndexOutOfBoundsException { } public void writelist() throws IOException{ }

How to Throw Exceptions Who can throw an exception? your code code from a package written by someone else such as the packages that come with the Java platform the Java runtime environment Always thrown with the throw statement

How to Throw Exceptions The Java platform provides numerous exception classes All the classes are descendants of the Throwable class throw somethrowableobject;

The throw Statement Requires a single argument: a throwable object instances of any subclass of the Throwable class public Object pop() { Object obj; if (size == 0) throw new EmptyStackException(); obj = objectat(size - 1); setobjectat(size - 1, null); size--; return obj; }

Throwable Class and Its Subclasses

Error and exception classes An Error: a dynamic linking failure or other hard failure in the Java virtual machine occurs simple programs typically do not catch or throw Errors An Exception: indicates that a problem occurred, but it is not a serious system problem most programs throw and catch objects that derive from the Exception class

Runtime Exceptions indicate incorrect use of an API NullPointerException which occurs when a method tries to access a member of an object through a null reference

Creating Exception Classes When to create an exception class? you need an exception type that isn't represented by those in the Java platform it helps users if they could differentiate your exceptions from the predefined ones the code throws more than one related exception

Creating Exception Classes A linked list class objectat(int n) throws an exception if n<0 or n> the number of objects currently in the list. firstobject() throws an exception if the list is empty. indexof(object o) throws an exception if the object passed into the method is not in the list.

Creating Exception Classes One possible class hierarchy for the exceptions thrown by the linked list

Unchecked Exceptions If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Advantage 1: Separating Error-Handling Code from "Regular" Code readfile { open the file; determine its size; allocate that much memory; read the file into memory; close the file;

Advantage 1: Separating Error- Handling Code from "Regular" Code What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed?

Advantage 1: Separating Error-Handling Code from "Regular" Code errorcodetype 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; } close the file; if (thefiledidntclose && errorcode == 0) { errorcode = -4; } else { errorcode = errorcode and -4; } } else { errorcode = -5; } return errorcode; }

Advantage 1: Separating Error-Handling Code from "Regular" Code 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; }

Advantage 2: Propagating Errors Up the Call Stack method1 { call method2; } method2 { call method3; } method3 { call readfile; }

Advantage 2: Propagating Errors Up the Call Stack method1 { errorcodetype error; error = call method2 if (error) doerrorprocessing; else proceed;} errorcodetype method2 { errorcodetype error; error = call method3; if (error) return error; else proceed;} errorcodetype method3 { errorcodetype error; error = call readfile; if (error) return error; else proceed; }

Advantage 2: Propagating Errors Up the Call Stack method1 { try { call method2; catch (exception e) { doerrorprocessing; method2 throws exception { call method3; method3 throws exception { call readfile;

Advantage 3: Grouping and Differentiating Error Types java.io > IOException descendant FileNotFoundException catch (IOException e) {... or catch (FileNotFoundException e) {... or catch (Exception e) { //A (too) general exception handler...

Problem Read data from the file Input.txt. The file should contain integer numbers, one per row. If the read value is an integer number, place it into the file Output.txt, otherwise generate an exception. The exception s handler should read a number from the keyboard and put it into the Output.txt file.

Solution public class MyException extends Exception{ private String s; private int row; public MyException(int r, String line){ s=line; row=r; } public String tostring(){ return String.format("Exception in line %d to the String %s", row, s);}

Solution import java.io.*; public class Client{ public static void main(string []arg){ BufferedReader in=null, ink=null; PrintStream out=null; String line; int row=1;

Solution try{ in = new BufferedReader(new InputStreamReader( new FileInputStream("Input.txt"))); ink = new BufferedReader(new InputStreamReader( System.in)); out = new PrintStream(new FileOutputStream("Output.txt")); //Read procedure catch(ioexception e) { System.out.println(e);}

Solution //Read procedure line=in.readline(); while(line!=null){ try{ for(int i=0;i<line.length();i++) if(!character.isdigit(line.charat(i))) throw new MyException(row, line); out.println(line); line=in.readline(); row++;} catch(myexception e){ System.out.println(e); System.out.println("Read a number from the keyboard"); line=ink.readline(); out.println(line);}}

Solution try{ //Previously presented } finally { try{ if(in!=null) in.close(); if(ink!=null) ink.close(); if(out!=null) out.close();} catch(ioexception e){ System.out.println(e);}

References The Java Tutorials. Exceptions. http://java.sun.com/docs/books/tuto rial/essential/exceptions/index.html