And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.

Slides:



Advertisements
Similar presentations
Exception Handling and Event 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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Exception Handling Exception handling (EH) allows a programmer to provide code in the program to handle run-time errors or exceptional situations – this.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 13 In a language without exception handling: When an exception occurs, control goes to the operating.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Chapter 14 Exception Handling and Event Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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.
ISBN Chapter 14 Exception Handling and Event Handling.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11 Exception Handling and Event Handling.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
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.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
May 21, ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)
Chapter 14 Exception Handling and Event Handling.
Object Oriented Programming
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
ISBN Chapter 14 Exception Handling and Event 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.
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.
COMP Exception Handling Yi Hong June 10, 2015.
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.
ISBN Chapter 14 Exception Handling and Event Handling.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
ICS 313: Programming Language Theory Chapter 14: Exceptions.
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.
ISBN Chapter 14 Exception Handling and Event Handling.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Java Exceptions a quick review….
Exception Handling C++.
Exception Handling and Event Handling
Exception Handling and Event Handling
similar concepts, different syntax
Java Programming Language
Exception Handling and Event Handling
Chapter 12 Exception Handling
Exception Handling and Event Handling
Web Design & Development Lecture 7
Exception Handling and Event Handling
Exception Handling and Event Handling
Exception and Event Handling
Exception Handling and Event Handling
Java Basics Exception Handling.
Exception Handling and Event Handling
Exception Handling.
Presentation transcript:

and other languages…

must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller Function label to subprogram Fortran strategy

 Error detection code is tedious to write and it clutters the program  Exception propagation allows a high level of reuse of exception handling code  Encourage programmers to consider all events that could occur that might need to be handled – especially checked exceptions.

An exception is an unusual event detectable by either hardware or software An exception is raised/thrown when its associated event occurs The exception handler code determines what to do

 How to bind an exception to a handler  What information to make available about exception  Is it possible to continue after an exception?  Does the language have any built-in exceptions?  Are there user-defined exception types  Is there a default exception handler?  Can exceptions be disabled? What decisions were made for Java?

Added to C++ in 1990 Exceptions are user- or library-defined (none in language definition) Exception Handlers Form (like Java): try { -- code that is expected to raise an exception } catch (formal parameter) { // only 1 parm -- handler code }... catch (formal parameter) { -- handler code }

catch is the name of all handlers--it is an overloaded name, so the formal parameter of each must be unique The formal parameter need not have a variable ◦ It can be simply a type name to distinguish the handler it is in from others, e.g. catch(int) rather than catch (int x) The formal parameter variable can be used to transfer information to the handler The formal parameter can be an ellipsis (…), in which case it handles all exceptions not yet handled Compare to Java: Possible to throw/catch an int? Does formal parameter need a variable? (yes) How does the handler get information? What mechanism is used in place of …? How does this work?

 Exceptions all raised explicitly by: throw expression;  expression may be a literal or variable of any type  A throw without an operand can only appear in a handler; when it appears, it simply re-raises the exception, which is then handled elsewhere Syntax to throw exception in Java?

Problem! main calls function a a calls function b exception occurs in b If no try/catch in b, exception propagates to a If no try/catch in a, exception propagates to main If no try/catch in main, execution terminates (in C++, can override default handler, named unexpected) Continuation. If exception is handled, execution continues after last catch (unless handler calls exit of course). main a b call Both Java and C++ propagate exceptions

 styleguide.googlecode.com/svn/trunk/cppguide.html#Exceptions  error-logic.html error-logic.html  style-no-exceptions-rule-what-about-multithreading style-no-exceptions-rule-what-about-multithreading  exceptions-be-used-conservatively exceptions-be-used-conservatively   Goto.pdf Put some thoughts on paper, be ready to share

 The Java library includes two subclasses of Throwable : – Error  Thrown by the Java interpreter for events such as heap overflow  Never handled by user programs – Exception  User-defined exceptions are usually subclasses of this  Has two predefined subclasses, IOException and RuntimeException (e.g., ArrayIndexOutOfBoundsException and NullPointerException)

Exceptions of class Error and RunTimeException and all of their descendants are called unchecked exceptions All other exceptions are called checked exceptions (compiler checks that your code handles – all exceptions occur at runtime) Methods containing code that can throw a checked exception must either: ◦ List the exception(s) in a throws clause, or ◦ Handle the exception (e.g., with try/catch) ◦ Example throws clause (not the same as throwing an exception!): public void myFunction() throws Exception

A method cannot declare more exceptions in its throws clause than the method it overrides. Example: If you override run in a Thread class, you cannot add a throws clause. A method that calls a method with a checked exception in its throws clause has three alternatives: 1. Catch and handle the exception 2. Catch the exception and throw an exception that is listed in its own throws clause 3. Declare that exception in its throws clause and do not handle it public void A() throws BadException { … } public void B() { … try { A() } catch (BadException e) { … } } public void C() throws AnException{ … try { A() } catch (BadException e) { throw (AnException) } } public void D() throws BadException { … A() … }

Can appear at the end of a try construct Form: finally {... } Purpose: To specify code that is to be executed, regardless of what happens in the try construct (e.g., to close file or database connection). Finally is executed even if there is a return statement in the block.

try { for (index = 0; index < 100; index++) { … if (…) { return; } //** end of if } //** end of try clause finally { … } //** end of try construct * Java exercise has examples to play with

 Exceptions are raised using the raise method of Kernel  The rescue clause is used to handle exceptions  Exceptions are instances of the Exception class (or a subclass)  Subclasses do not add methods or behavior, but allow exceptions to be categorized  Most exceptions extend StandardError  Other exceptions are low-level, typically not handled by programs * Exception info directly from The Ruby Programming Language

 message method returns a string – more suitable for programmers than end users  backtrace returns the call stack array of strings filename : linenumber in methodname

 fail is synonym (use if expect program to end)  Several ways to invoke raise: with no arguments. If inside rescue, re-raises same exception, otherwise raises RuntimeError with single Exception object. Not common. with single String argument. Creates RuntimeError with that string as message. Very common. with exception object, string (for message) and array of strings (for backtrace).

def factorial(n) raise "bad argument" if n < 1 # raise ArgumentError if n < 1 # raise ArgumentError, "Expected argument >= 1, got #{n}" if n < 1 return 1 if n == 1 n * factorial(n-1) end  Can provide a custom stack trace def factorial4(n) if n < 1 raise ArgumentError, "Expected argument >= 1, got #{n}", caller end return 1 if n == 1 n * factorial(n-1) end

 rescue is part of Ruby language (not a Kernel method)  clause that can be attached to other Ruby statements  typically attached to begin begin # statements, possible exceptions rescue # code to deal with exceptions end # if no exception, code continues here, code in rescue is not executed

 rescue handles any StandardError  global variable $! refers to raised exception  better to specify variable in rescue begin x = factorial(0) rescue => ex puts "#{ex.class}: #{ex.message}" end

def factorial5(n) raise TypeError, “Need integer" if not n.is_a? Integer raise ArgumentError, “Need argument >= 1, got #{n}" if n < 1 return 1 if n == 1 n * factorial(n-1) end begin x = factorial5("a") rescue ArgumentError => ex puts "Try again with argument > 1" rescue TypeError => ex puts "Try again with an integer" end Does the order matter?

def explode raise "bam!" if rand(10) == 0 end def risky begin 10.times do explode #raises error ~10% of time end rescue TypeError # won't catch RuntimeError puts $! end# RuntimeError not handled, will propagate "hello" # if no exception end def defuse begin puts risky rescue RuntimeError => e# handle propagated error puts e.message end defuse QUICK EX: Trace code

 retry – with rescue, reruns block of code that rescue is attached to. Useful for transient failures such as overloaded server. Be sure to limit number of retries.  ensure – code that always runs, for housekeeping like disconnecting from database, closing files, etc.  not covered: subtle details for ensure  rescue can be used as a statement modifier (y = factorial(x) rescue 0 #returns 0 if error)

 similar to a labeled break, but can break out of multiple levels  not used for exception handling  used infrequently, details not covered

 C++  Topic Exploration  Java