Ruby - Handling multiple exception types

Introduction

You can take different actions for different exceptions.

You can do that by adding multiple rescue clauses.

Each rescue clause can handle multiple exception types, with the exception class names separated by commas.

Demo

def calc( val1, val2 )
    begin# w ww.j a v  a2  s  .c  o  m
        result = val1 / val2
    rescue TypeError, NoMethodError => e
        puts( e.class )
        puts( e )
        puts( "One of the values is not a number!" )
        result = nil
    rescue Exception => e
        puts( e.class )
        puts( e )
        result = nil
    end
    return result
end


calc( 20, 0 )
calc( 20, "100" )
calc( "100", 100 )

Result

When handling multiple exception types, you should always put the rescue clauses dealing with specific exceptions first and then follow these with rescue clauses dealing with more generalized exceptions.

Related Topic