Course Content

Course Content

FAQs

Exception handling is a good way to catch errors in Ruby programs. There are three ways of handling exceptions:

  • Catch an exception and handle it by returning a message or aborting execution with an error code.
  • Receive an exception and raise another exception that you can catch later on, which will resume the execution of your own code after raising another exception.
  • Ignore exceptions completely and let them bubble up until they reach the top level where they can be handled by your application's main logic

The following are the different ways to handle exceptions:

  • Raise an exception in a try block and handle it in a catch block
  • Throw an exception and catch it in a try block, with final blocks if needed
  • Catch an exception and return a default value or null value

Exceptions can be handled in multiple ways:

  • use try/catch blocks to catch exceptions and handle them accordingly
  • use a rescue block to handle exceptions that were not caught by the try/catch blocks
  • use super() to call the parent class's method if an exception was not caught by the try/catch blocks

Some of the most common exceptions you may run into when using Ruby are those related to missing data, division by zero, and undefined methods.

A common pattern in Ruby is to raise exceptions when a condition is not met. For example, the following code will raise an exception if the number of items in the list is not prime:

  • def divisible_by?(number)
  • if number % 2 == 0
  • raise "Divisible by 2"
  • end

Share With Friend

Have a friend to whom you would want to share this course?

Download LearnVern App

App Preview Image
App QR Code Image
Code Scan or Download the app
Google Play Store
Apple App Store
598K+ Downloads
App Download Section Circle 1
4.57 Avg. Ratings
App Download Section Circle 2
15K+ Reviews
App Download Section Circle 3
  • Learn anywhere on the go
  • Get regular updates about your enrolled or new courses
  • Share content with your friends
  • Evaluate your progress through practice tests
  • No internet connection needed
  • Enroll for the webinar and join at the time of the webinar from anywhere