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

Similar documents
CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exceptions. CSC207 Winter 2017

ECE 122. Engineering Problem Solving with Java

BBM 102 Introduction to Programming II Spring Exceptions

EXCEPTION HANDLING. Summer 2018

Data Structures. 02 Exception Handling

14. Exception Handling

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

BBM 102 Introduction to Programming II Spring 2017

Sri Vidya College of Engineering & Technology Question Bank

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Chapter 13 Exception Handling

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

Internal Classes and Exceptions

Errors and Exceptions

Object Oriented Programming

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

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

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

Exceptions Handling Errors using Exceptions

17. Handling Runtime Problems

More on Exception Handling

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

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

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

C16b: Exception Handling

Fundamentals of Object Oriented Programming

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

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

Full file at Chapter 2 - Inheritance and Exception Handling

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

More on Exception Handling

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

Exceptions - Example. Exceptions - Example

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

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

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

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

Introduction to Software Design

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

Exceptions and Libraries

Object Oriented Programming

CS 11 java track: lecture 3

COE318 Lecture Notes Week 10 (Nov 7, 2011)

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

Programming II (CS300)

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

Exception-Handling Overview

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

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

Correctness and Robustness

CS 3 Introduction to Software Engineering. 3: Exceptions

EXCEPTIONS. Java Programming

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

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

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

Exception Handling in Java

ITI Introduction to Computing II


2.6 Error, exception and event handling

Programming Languages and Techniques (CIS120)

Chapter 12 Exception Handling

ITI Introduction to Computing II

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

Chapter 14. Exception Handling and Event Handling ISBN

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

Program Correctness and Efficiency. Chapter 2

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

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

Writing your own Exceptions. How to extend Exception

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

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

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

Java Programming Unit 7. Error Handling. Excep8ons.

CSC207 Winter Section L5101 Paul Gries

Exceptions. What exceptional things might our programs run in to?

Exception handling in Java. J. Pöial

ASSERTIONS AND LOGGING

More fun with Java. Packages. Simple Declarations. Import. Basic Structure of a Java Program. /* a comment */ // a comment

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

6.Introducing Classes 9. Exceptions

Unit 5 - Exception Handling & Multithreaded

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

COMP1008 Exceptions. Runtime Error

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

Programming II (CS300)

16-Dec-10. Consider the following method:

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

Chapter 14. Exception Handling and Event Handling

Software Practice 1 - Error Handling

Principles of Software Construction: Objects, Design and Concurrency. Exceptions, scope, static data and methods, and Generics.

Introduction to Java. Handout-3a. cs402 - Spring

Advanced Flow of Control -- Introduction

Preconditions. CMSC 330: Organization of Programming Languages. Signaling Errors. Dealing with Errors

Typecasts and Dynamic Dispatch. Dynamic dispatch

Transcription:

National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java

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 error handling from main business logic Based on ideas developed in Ada, Eiffel and C++ Java has a uniform approach for handling all synchronous errors From very unusual (e.g. out of memory) To more common ones your program should check itself (e.g. index out of bounds) From Java run-time system errors (e.g., divide by zero) To errors that programmers detect and raise deliberately

Throwing and catching An error can throw an exception throw <exception object>; By default, exceptions result in the thread terminating after printing an error message However, exception handlers can catch specified exceptions and recover from error catch (<exception type> e) { //statements that handle the exception

Throwing an exception Example creates a subclass of Exception and throws an exception: class MyException extends Exception { class MyClass { void oops() { if (/* no error occurred */) { /* normal processing */ else { /* error occurred */ throw new MyException(); //oops //class MyClass

Exceptional flow of control Exceptions break the normal flow of control. When an exception occurs, the statement that would normally execute next is not executed. What happens instead depends on: whether the exception is caught, where it is caught, what statements are executed in the catch block, and whether you have a finally block.

Approaches to handling an exception 1. Prevent the exception from happening 2. Catch it in the method in which it occurs, and either a. Fix up the problem and resume normal execution b. Rethrow it c. Throw a different exception 3. Declare that the method throws the exception 4. With 1. and 2.a. the caller never knows there was an error. 5. With 2.b., 2.c., and 3., if the caller does not handle the exception, the program will terminate and display a stack trace

Exception hierarchy Java organizes exceptions in inheritance tree: Throwable Error Exception RuntimeException TooManyListenersException IOException AWTException

Java is strict Unlike C++, is quite strict about catching exceptions If it is a checked exception (all except Error, RuntimeException and their subclasses), Java compiler forces the caller must either catch it or explicitly re-throw it with an exception specification. Why is this a good idea? By enforcing exception specifications from top to bottom, Java guarantees exception correctness at compile time. Here s a method that ducks out of catching an exception by explicitly re-throwing it: void f() throws toobig, toosmall, divzero { The caller of this method now must either catch these exceptions or rethrow them in its specification.

Error and RuntimeException Error unchecked, thus need not be in throws clause Serious system problems (e.g. ThreadDeath, OutOfMemoryError) It s very unlikely that the program will be able to recover, so generally you should NOT catch these. RuntimeException unchecked, thus need not be in throws clause Also can occur almost anywhere, e.g. ArithmeticException, NullPointerException, IndexOutOfBoundsException Try to prevent them from happening in the first place! System will print stop program and print a trace

Catching an exception try { // statement that could throw an exception catch (<exception type> e) { // statements that handle the exception catch (<exception type> e) { //e higher in hierarchy // statements that handle the exception finally { // release resources //other statements At most one catch block executes finally block always executes once, whether there s an error or not

Execution of try catch blocks For normal execution: try block executes, then finally block executes, then other statements execute When an error is caught and the catch block throws an exception or returns: try block is interrupted catch block executes (until throw or return statement) finally block executes When error is caught and catch block doesn t throw an exception or return: try block is interrupted catch block executes finally block executes other statements execute When an error occurs that is not caught: try block is interrupted finally block executes

Example: try { p.a = 10; catch (NullPointerException e) { System.out.println("p was null"); catch (Exception e) { System.out.println("other error occurred"); catch (Object obj) { System.out.println("Who threw that object?"); finally { System.out.println( final processing"); System.out.println( Continue with more statements");

Catch processing When an exception occurs, the nested try/catch statements are searched for a catch parameter matching the exception class A parameter is said to match the exception if it: is the same class as the exception; or is a superclass of the exception; or if the parameter is an interface, the exception class implements the interface. The first try/catch statement that has a parameter that matches the exception has its catch statement executed. After the catch statement executes, execution resumes with the finally statement, then the statements after the try/catch statement.

Catch processing example print("now"); try { print("is "); throw new MyException(); print("a "); catch(myexception e) { print("the "); print("time\n"); Prints "now is the time". Note that exceptions don't have to be used only for error handling Would it be a good idea to exceptions for non-error processing? But any other use is likely to result in code that's hard to understand.

Declaring an exception type Inherit from an existing exception type. Provide a default constructor and a constructor with one arg, type String. Both should call super(astring); Example: class MyThrowable extends Throwable { // checked exception MyThrowable () { super ("Generated MyThrowable"); MyThrowable (String s) { super (s);

Declaring an exception type Inherit from an existing exception type. Provide a default constructor and a constructor with one arg, type String. Both should call super(astring); class ErrorThrower { public void errormethod() throws MyThrowable { throw new MyThrowable ("ErrorThrower"); // forces this method to declare MyThrowable

Exceptions are ubiquitous in Java Exception handling required for all read methods Also many other system methods If you use one of Java's built in class methods and it throws an exception, you must catch it (i.e., surround it in a try/catch block) or rethrow it, or you will get a compile time error: char ch; try { ch = (char) System.in.read(); catch (IOException e) { System.err.println(e); return;