Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.

Slides:



Advertisements
Similar presentations
Yoshi
Advertisements

Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
COMP 121 Week 5: Exceptions and Exception Handling.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Understand Error Handling Software Development Fundamentals LESSON 1.4.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Handling Errors with Exception (in Java) Project 10 CSC 420.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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 Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
Exception Handling. Definition  The term exception is shorthand for the phrase "exceptional event.“  An exception is an event, which occurs during the.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
Java Programming: Guided Learning with Early Objects
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Chapter 8-Exception Handling/ Robust Programming.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lecture 18B Exception Handling and Richard Gesick.
Geoff Holmes Week 5 problems Handling Throwing Catching Multiple exceptions Finally clause Examples Exception Handling.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Java Exceptions a quick review….
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Exceptions 10-Nov-18.
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exception Handling Contents
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation Correct use of exception handling Benefits of exception handling Summary

Exceptions in OO Programming Errors The Golden Rule of Programming: Errors occur in software programs! How do we deal with errors? Try to minimise their occurrence (bug-checking). Prevent invalid data from entering the system (validation). Handling errors as they occur (exception handling). Exception handling is a coding mechanism which handles errors as they occur and prevents the program from crashing

Exceptions in OO Programming Exceptions Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. What kinds of exceptions can occur in Java? Input/Output exceptions Memory exceptions Mathematical exceptions Pointer exceptions, and many more... When an exception occurs it is said that the exception has been ‘thrown’.

Exceptions in OO Programming Checked and Unchecked Unchecked exceptions are the type of exceptions we don't want to have to catch. For example:nAverage = nSum/nTotalUsers; Can generate a divide-by-zero exception! We don't put try/catch round every bit of maths. Checked exceptions are the ones we do need to catch and process. For example we may need to give feedback to a user to remind them to put a CD into a drive or to add paper to a printer.

Exceptions in OO Programming Handling Exceptions The mechanism for handling exceptions during program execution is the Try-Catch-Finally block. The general format for using these statements is: try { // some Java code that can cause an exception } catch(exception thrown) { // code to handle the exception } finally { // tidy up code (optional) }

Exceptions in OO Programming The Try Block The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block. In general, a try block looks like this: try { Java statements } The segment of code labelled Java statements is composed of one or more legal Java statements that could throw an exception.

Exceptions in OO Programming The Catch Block The try statement defines the scope of the exceptions which might be thrown. You provide one or more catch blocks directly after the try block: [why multiple catch blocks?] try {... } catch (... ) {... } catch (... ) {... }

Exceptions in OO Programming The Finally Block The final step in setting up an exception handler is providing a mechanism for cleaning up the state of the method before (possibly) allowing control to be passed to a different part of the program. You do this by enclosing the cleanup code within a finally block. The finally block comes in useful when a piece of code must be executed regardless of whether the try block was successful or not. e.g. closing a File object.

Exceptions in OO Programming File Example try {BufferedReader br = new BufferedReader(newFileReader("MyFile.txt")); String line = br.readLine(); } catch(FileNotFoundException fnfe) {System.out.println("File MyFile.txt not found."); } catch(IOException ioe) {System.out.println("Unable to read from MyFile.txt"); } return line;

Exceptions in OO Programming File Example The constructor of FileReader throws a FileNotFoundException (a subclass of IOException) if the specified file is not found. Otherwise, if the file exists but for some reason the readLine() method can't read from it FileReader throws an IOException. (maybe the file has user access privileges or is currently locked by another user)

Exceptions in OO Programming Propagation of Exceptions You can decide to not deal with an exception within a particular method, Then you must declare that the method can throw exceptions. These exceptions are then passed up the chain of calling methods. e.g. if some part of your sub-system produces an exception but you want your user-interface classes to deal with it then you can. All intervening methods must have their signatures set to throw the exception(s).

Exceptions in OO Programming Method Signatures A try-catch block must then be placed around the call to the top-level intervening method. If you are going to propagate an exception from a method then the method signature has to specify this. public String readHeader() throws FileNotFoundException, IOException {// method code }

Exceptions in OO Programming Example method1 {try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }

Exceptions in OO Programming Correct Use Often, developers add the mechanism as an afterthought. Significant re-engineering during the coding stage can make this oversight an expensive proposition. A clear and detailed exception-handling strategy pays off in the form of robust code, which in turn, enhances user value.

Exceptions in OO Programming Benefits Java's exception-handling mechanism offers the following benefits: It separates the working/functional code from the error-handling code by way of try-catch clauses. It allows a clean path for error propagation. If the called method encounters a situation it can't manage, it can throw an exception and let the calling method deal with it.

Exceptions in OO Programming Benefits Java's exception-handling mechanism offers the following benefits: By enlisting the compiler to ensure that "exceptional" situations are anticipated and accounted for, it enforces powerful coding. Forcing the developer to code for exceptions improves the quality of information for users of the code – compare with C++ where exceptions are “unchecked” and often undocumented.

Exceptions in OO Programming Problems with Exceptions It can be hard to propagate exceptions at the appropriate level of abstraction, for example; A “SQLException” at one level could be a “DuplicateUserIDException” elsewhere. Sometimes handling exceptions properly is a lot of work for extremely rare cases. Lazy developers can easily avoid handling exceptions properly – and often do.

Exceptions in OO Programming Summary Errors can always occur. By using the exception handling mechanism, you can let your code deal with the error and continue execution. The exception handling mechanism separates your code from the code which deals with the error. This can be code that is placed further up the method call stack. Use of the exception handling mechanism leads to robust applications that users can feel confident with.