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 0Each kind of failure is its own class. A few common ones:
ZeroDivisionError: dividing an integer by zeroArgumentError: 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
BeginnerRead 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-zero→ZeroDivisionErrornil-method→NoMethodErrorbad-integer→ArgumentErrorwrong-type→TypeError- 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 zeroArgumentError: 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 0Every 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier32D Arrays
2D Array BasicsAccessing 2D ElementsIterating Over 2D ArraysCommon 2D PatternsRecap - Matrix Operations9Error Handling
What is an Exception?begin / rescueMultiple rescue Clausesensure and raiseRecap - Safe Calculator