Explain the exceptions in Ruby.

Source: Internet
Author: User

Explain the exceptions in Ruby.

Exceptions and executions are always associated. If you open a non-existent file and do not properly handle this situation, your program is considered to be of low quality.

If an exception occurs, the program stops. Exceptions are used to handle various types of errors that may occur during program execution. Therefore, appropriate actions should be taken so that the program will not be completely stopped.

Ruby provides a perfect mechanism for exception handling. We can attach code that may throw exceptions to the begin/end block and use the rescue clause to tell Ruby the exception type to be handled perfectly.
Syntax

Begin #-rescue OneTypeOfException #-rescue AnotherTypeOfException #-else # other exceptions ensure # Always executed end

Everything from begin to rescue is protected. If an exception occurs during code block execution, the control is passed to the block between rescue and end.

For each rescue clause in the begin block, Ruby compares the thrown exceptions with each parameter in turn. If the exception named in the rescue clause is of the same type as the currently thrown exception, or the parent class of the exception, the match is successful.

If the exception does not match all specified error types, we can use an else clause after all rescue clauses.
Instance

#!/usr/bin/ruby begin  file = open("/unexistant_file")  if file   puts "File opened successfully"  endrescue   file = STDINendprint file, "==", STDIN, "\n"

This will produce the following results. As you can see, STDIN replaces file because opening fails.
# <IO: 0xb7d16f84 >=# <IO: 0xb7d16f84>
Use retry statements

You can use the rescue block to capture exceptions, and then use the retry statement to execute the begin block from the beginning.
Syntax

Begin # The exception thrown by this code will be captured by the following rescue clause rescue # this block will capture all types of exceptions retry # This will move the control to the beginning of the begin end instance #! /Usr/bin/ruby begin file = open ("/unexistant_file") if file puts "File opened successfully" endrescue fname = "existant_file" retryend

The process is as follows:

  1. An exception occurred when opening.
  2. Jump to rescue. Fname is assigned again.
  3. Use retry to jump to the beginning of begin.
  4. The file is successfully opened this time.
  5. Continue the basic process.

Note: If the renamed file does not exist, the Force code will try it infinitely. Therefore, use retry with caution when handling exceptions.
Use raise statements

You can use the raise statement to throw an exception. The following method throws an exception during the call. The second message is output.
Syntax

raise OR raise "Error Message" OR raise ExceptionType, "Error Message" OR raise ExceptionType, "Error Message" condition

The first method is to simply re-Throw the current exception (if there is no current exception, a RuntimeError is thrown ). This is used in the exception handling program that needs to be interpreted before an exception is passed in.

In the second form, create a new RuntimeError exception and set its message to a given string. This exception is then thrown to the call stack.

The third method creates an exception using the first parameter, and then sets the relevant message as the second parameter.

The fourth form is similar to the third form. You can add any additional conditional statements (such as unless) to throw an exception.
Instance

#!/usr/bin/ruby begin   puts 'I am before the raise.'   raise 'An error has occurred.'   puts 'I am after the raise.' rescue   puts 'I am rescued.' end puts 'I am after the begin block.' 

This produces the following results:

I am before the raise. I am rescued. I am after the begin block. 

Another example that demonstrates raise usage:

#!/usr/bin/ruby begin  raise 'A test exception.' rescue Exception => e  puts e.message  puts e.backtrace.inspect end 

This produces the following results:

A test exception.["main.rb:4"]

Use the ensure statement

Sometimes, whether or not an exception is thrown, you must ensure that some processing is completed at the end of the code block. For example, you may have opened a file during loading. When you exit the block, make sure to close the file.

This is what the ensure clause does. Ensure is placed after the last rescue clause and contains a code block that is always executed when the block is terminated. It has nothing to do with whether the block Exits normally, whether to throw and handle exceptions, and whether to terminate because of an uncaptured exception. The ensure block will always run.
Syntax

Begin #.. process #.. throw an exception rescue #.. processing error ensure #.. finally, make sure to execute #.. this will always execute the end instance begin raise 'a test exception. 'Rescue Exception => e puts e. message puts e. backtrace. inspectensure puts "Ensuring execution" end

This produces the following results:

A test exception.["main.rb:4"]Ensuring execution

Use else statements

If an else clause is provided, it is usually placed after the rescue clause and before any ensure.

The subject of the else clause is executed only when the Code body does not throw an exception.
Syntax

Begin #.. process #.. throw an exception rescue #.. processing error else #.. if no exception exists, execute ensure #.. finally, make sure to execute #.. this will always execute the end instance begin # Throw 'a test exception. 'puts "I'm not raising exception" rescue Exception => e puts e. message puts e. backtrace. inspectelse puts "Congratulations -- no errors! "Ensure puts" Ensuring execution "end

This produces the following results:

I'm not raising exceptionCongratulations-- no errors!Ensuring execution

Use $! Variables can capture thrown error messages.
Catch and Throw

The exception mechanism of raise and rescue can discard execution when an error occurs. Sometimes it is necessary to jump out of some deep nested structures during normal processing. In this case, catch and throw are used.

Catch defines a block that uses the given name (can be Symbol or String) as the tag. The block will be executed normally and a throw will be encountered.
Syntax

Throw: lablename #.. this will not be executed catch: lablename do #.. match the catchend OR throw that will be executed after a throw: lablename condition #.. this will not be executed catch: lablename do #.. match the catchend to be executed after a throw is encountered

Instance

In the following instance, if you type '! 'Use a throw to terminate interaction with the user in response to any prompt.

Def promptAndGet (prompt) print prompt res = readline. chomp throw: quitRequested if res = "! "Return resend catch: quitRequested do name = promptAndGet (" Name: ") age = promptAndGet (" Age: ") sex = promptAndGet (" Sex :")#.. # Processing Information endpromptAndGet ("Name :")

The above program requires manual interaction. You can try it on your computer. This produces the following results:

Name: Ruby on RailsAge: 3Sex: !Name:Just Ruby

Exception

Ruby standard classes and modules throw exceptions. All Exception classes constitute a hierarchy, including the Exception class at the top. The next layer has seven different types:

  1. Interrupt
  2. NoMemoryError
  3. SignalException
  4. ScriptError
  5. StandardError
  6. SystemExit
  7. Fatal is another exception in this layer, but the Ruby interpreter only uses it internally.

Both ScriptError and StandardError have some subclasses, but we do not need to know these details here. The most important thing is to create our own Exception classes. They must be Exception classes or subclass of their children.

Let's look at an instance:

class FileSaveError < StandardError  attr_reader :reason  def initialize(reason)   @reason = reason  endend

Now, let's look at the following instance and use the above exception:

File. open (path, "w") do | file | begin # Write Data... rescue # error raise FileSaveError. new ($ !) Endend

The most important line here is raise FileSaveError. new ($ !). We call raise to indicate that an exception has occurred and pass it to a new instance of FileSaveError. Data Writing fails due to a specific exception.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.