Object Oriented Programming

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
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.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
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.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
1. 2 Examples for Exception?... An exception is an abnormal condition that arises in a code sequence at run time (Run time error). In other computer languages.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 Nested Classes O. 2 Possible to declare a class within another class; called nested classes Nested class should have some specific association with.
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. 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.
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Slides Credit Umair Javed LUMS Web Application Development.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
VB.Net - Exceptions Copyright © Martin Schray
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
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.
MCS 270 Spring 2014 Object-Oriented Software Development.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
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.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Appendix H Exception Handling: A Deeper Look
Exception Handling Chapter 9.
OBJECT ORIENTED PROGRAMMING
Exception Handling Chapter 9 Edited by JJ.
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.
Exception Handling and Event Handling
Exception Handling.
Presentation transcript:

Object Oriented Programming

Topic to be covered today Exception Handling

Exceptions Exception is an abnormal condition that arises when executing a program. In the languages that do not support exception handling, errors must be checked and handled manually, usually through the use of error codes. In contrast, Java: provides syntactic mechanisms to signal, detect and handle errors ensures a clean separation between the code executed in the absence of errors and the code to handle various kinds of errors brings run-time error management into object-oriented programming

Exception Handling An exception is an object that describes an exceptional condition (error) that has occurred when executing a program. Exception handling involves the following: when an error occurs, an object (exception) representing this error is created and thrown in the method that caused it that method may choose to handle the exception itself or pass it on either way, at some point, the exception is caught and processed

Exception Sources Exceptions can be: generated by the Java run-time system Fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. manually generated by programmer’s code Such exceptions are typically used to report some error conditions to the caller of a method.

Exception Constructs Five constructs are used in exception handling: try – a block surrounding program statements to monitor for exceptions catch – together with try, catches specific kinds of exceptions and handles them in some way finally – specifies any code that absolutely must be executed whether or not an exception occurs throw – used to throw a specific exception from the program throws – specifies which exceptions a given method can throw

Exception-Handling Block General form: where: 1) try { … } is the block of code to monitor for exceptions 2) catch(Exception ex) { … } is exception handler for theexception Exception 3) finally { … } is the block of code to execute before the try block ends

Exception Hierarchy All exceptions are sub-classes of the build-in class Throwable. Throwable contains two immediate sub-classes: Exception – exceptional conditions that programs should catch The class includes: a) RuntimeException – defined automatically for user programs to include: division by zero, invalid array indexing, etc. b) use-defined exception classes Error – exceptions used by Java to indicate errors with the runtime environment; user programs are not supposed to catch them

Uncaught Exception What happens when exceptions are not handled? When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and throws this object. This will cause the execution of Exc0 to stop – once an exception has been thrown it must be caught by an exception handler and dealt with.

Default Exception Handler As we have not provided any exception handler, the exception is caught by the default handler provided by the Java run-time system. This default handler: displays a string describing the exception, prints the stack trace from the point where the exception occurred terminates the program Any exception not caught by the user program is ultimately processed by the default handler.

Own Exception Handling Default exception handling is basically useful for debugging. Normally, we want to handle exceptions ourselves because: if we detected the error, we can try to fix it we prevent the program from automatically terminating Exception handling is done through the try and catch block.

Try and Catch Try and catch: try surrounds any code we want to monitor for exceptions catch specifies which exception we want to handle and how. When an exception is thrown in the try block:

Try and Catch control moves immediately to the catch block: The exception is handled and the execution resumes. The scope of catch is restricted to the immediately preceding try statement - it cannot catch exceptions thrown by another try statements.

Try and Catch Resumption occurs with the next statement after the try/catch block: Not with the next statement after a = 42/d; which caused the exception!

Exception Display All exception classes inherit from the Throwable class. Throwable overrides toString() to describe the exception textually: The following text will be displayed:

Multiple Catch Clauses When more than one exception can be raised by a single piece of code, several catch clauses can be used with one try block: each catch catches a different kind of exception when an exception is thrown, the first one whose type matches that of the exception is executed after one catch executes, the other are bypassed and the execution continues after the try/catch block

Order of Multiple Catch Clauses Order is important: catch clauses are inspected top-down a clause using a super-class will catch all sub-class exceptions Therefore, specific exceptions should appear before more general ones. In particular, exception sub-classes must appear before super-classes.

Example: Multiple Catch Order A try block with two catch clauses: This exception is more general but occurs first:

Example: Multiple Catch Order This exception is more specific but occurs last: The second clause will never get executed. A compile-time error (unreachable code) will be raised.

Nested Try statements The try statements can be nested: if an inner try does not catch a particular exception the exception is inspected by the outer try block this continues until: one of the catch statements succeeds or all the nested try statements are exhausted in the latter case, the Java run-time system will handle the exception

Throwing Exceptions So far, we were only catching the exceptions thrown by the Java system. In fact, a user program may throw an exception explicitly: throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or its subclass.

Throw Followup Once an exception is thrown by: throw ThrowableInstance; the flow of control stops immediately the nearest enclosing try statement is inspected if it has a catch statement that matches the type of exception: if one exists, control is transferred to that statement otherwise, the next enclosing try statement is examined if no enclosing try statement has a corresponding catch clause, the default exception handler halts the program and prints the stack

Creating Exceptions Two ways to obtain a Throwable instance: creating one with the new operator All Java built-in exceptions have at least two constructors: one without parameters and another with one String parameter: throw new NullPointerException("demo"); using a parameter of the catch clause try { … } catch(Throwable e) { … e … }

throws declaration If a method is capable of causing an exception that it does not handle, it must specify this behavior by the throws clause in its declaration: type name(parameter-list) throws exception-list {…} where exception-list is a comma-separated list of all types of exceptions that a method might throw. All exceptions must be listed except Error and RuntimeException or any of their subclasses, otherwise a compile-time error occurs.

Motivating Finally When an exception is thrown: the execution of a method is changed the method may even return prematurely. This may be a problem in many situations. For instance, if a method opens a file on entry and closes on exit; exception handling should not bypass the proper closure of the file. The finally block is used to address this problem.

finally Clause The try/catch statement requires at least one catch or finally clause, although both are optional: try { … } catch(Exception1 ex1) { … } … finally { … } Executed after try/catch whether of not the exception is thrown. Any time a method is to return to a caller from inside the try/catch block via: uncaught exception or explicit return the finally clause is executed just before the method returns.

Example: finally Three methods to exit in various ways. procA prematurely breaks out of the try by throwing an exception, the finally clause is executed on the way out:

Example: finally procB’s try statement is exited via a return statement, the finally clause is executed before procB returns:

Example: finally In procC, the try statement executes normally without error, however the finally clause is still executed:

Example: finally Demonstration of the three methods: