try-catch

try catch blocks for Ruby!

Try catch Block Chain use case

if you new to ruby and missing the try catch block here is a simple one for you


require 'try-catch'

try { hello world }.catch{ "not hello world " }
#> "not hello world"

try { "hello world".asdaf }.catch( NoMethodError ) { |ex| "there is and error, because #{ex}" }
#> there is and error, because undefined method `asdaf' for "hello world":String

#> you can cain up multiple catch for specific error
try { "hello world".asdaf }.catch( NoMethodError ) { |ex| "there is and error, because #{ex}" }

puts try { "hello world".asdaf }.catch(ArgumentError) { "it was and argument error" }.catch( NoMethodError ) { |ex| "bla bla #{ex}" }
#> "bla bla undefined method `asdaf' for "hello world":String"

The each line style


    try { puts "hello world".asdf }
    catch { |ex| puts ex.to_s.upcase  }
    #> UNDEFINED METHOD `ASDF' FOR "HELLO WORLD":STRING

or in each line version with specific Exception case


    try { puts "hello world".asdf }
    catch(ArgumentError) { |ex| puts ex.to_s.capitalize  }
    catch(NoMethodError) { |ex| puts ex.to_s.upcase  }

Happy Coding!