1 / 25

Ruby Exceptions

Ruby Exceptions. and other languages… . What if no exceptions?. Function. Caller. return status. label to subprogram. Function. Caller. Fortran strategy. must remember to check return value OR, must pass label/exception handler to every function. Advantages of exceptions.

varana
Download Presentation

Ruby Exceptions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Ruby Exceptions and other languages…

  2. What if no exceptions? Function Caller return status label to subprogram Function Caller Fortran strategy • must remember to check return value • OR, must pass label/exception handler to every function

  3. Advantages of exceptions 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.

  4. Terminology Review • An exception is an unusual event detectable by either hardware or software • An exception israised/thrownwhen its associated event occurs • The exception handler code determines what to do

  5. Design Decisions What decisions were made for Java? 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?

  6. Exception Handling in C++ • 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 }

  7. C++ catch • 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? • 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 handle

  8. C++ throw Syntax to throw exception in Java? 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

  9. Exception Propagation main 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). call a call b Problem! Both Java and C++ propagate exceptions

  10. Java Exception Handling • 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)

  11. Checked and Unchecked (review) • 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

  12. Java Details • 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: • Catch and handle the exception • Catch the exception and throw an exception that is listed in its own throws clause • 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() … }

  13. Java Finally • 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.

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

  15. So what about Ruby?* * Exception info directly from The Ruby Programming Language Exceptions are raised using the raise method of Kernel The rescueclause 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

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

  17. raising an exception • 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).

  18. Example 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

  19. capturing an exception • 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

  20. handling the exception • 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

  21. handling multiple types Does the order matter? 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

  22. propagating exceptions QUICK EX: Trace code 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 end defuse

  23. Other options 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)

  24. throw/catch similar to a labeled break, but can break out of multiple levels notused for exception handling used infrequently, details not covered

  25. Topic: Exceptions • Review the following websites, and/or find some of your own that discuss good practices for Exception handling. • Be prepared to discuss your “top 3” – the practices/advice you think will be most useful. • Sites: • http://blog.rubybestpractices.com/posts/rklemme/003-The_Universe_between_begin_and_end.html http://stackoverflow.com/questions/4375888/best-practice-using-system-supplied-or-custom-exceptions-for-error-conditions-i • http://today.java.net/pub/a/today/2003/12/04/exceptions.html • http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html

More Related