Menu
Coddy logo textTech

What is an Exception?

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 43 of 56.

When something goes wrong at runtime, dividing by zero, parsing "abc" as an integer, calling a method on nil: Ruby raises an exception. The program stops, and Ruby prints what happened along with where it happened.

10 / 0
# ZeroDivisionError: divided by 0

Each kind of failure is its own class. A few common ones:

  • ZeroDivisionError: dividing an integer by zero
  • ArgumentError: wrong arguments passed to a method (Integer("abc"))
  • NoMethodError: calling a method the receiver doesn't have (nil.upcase)
  • TypeError: operation on the wrong kind of object ("a" + 1)

Every exception class has a .message: the human-readable description Ruby prints when the exception is unhandled. The next lessons show how to catch these exceptions so your program keeps running.

challenge icon

Challenge

Beginner

Read a single line of input, a single Ruby expression name. Print the name of the exception class Ruby would raise for it. Use a case statement (no real raising needed):

  • divide-by-zeroZeroDivisionError
  • nil-methodNoMethodError
  • bad-integerArgumentError
  • wrong-typeTypeError
  • anything else → Unknown

For input nil-method, the output is NoMethodError.

Cheat sheet

When something goes wrong at runtime, Ruby raises an exception and the program stops. Common exception classes:

  • ZeroDivisionError: dividing an integer by zero
  • ArgumentError: wrong arguments (e.g. Integer("abc"))
  • NoMethodError: calling a method the receiver doesn't have (e.g. nil.upcase)
  • TypeError: operation on the wrong kind of object (e.g. "a" + 1)
10 / 0
# ZeroDivisionError: divided by 0

Every exception object has a .message with a human-readable description.

Try it yourself

kind = gets.chomp

# TODO: case kind ... print the matching exception class name
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow