d745f961b2cea85aadc930c9a651c33b2c1db55e
[ruby_koans.git] / koans / about_exceptions.rb
1 require File.expand_path(File.dirname(__FILE__) + '/edgecase')
2
3 class AboutExceptions < EdgeCase::Koan
4
5   class MySpecialError < RuntimeError
6   end
7
8   def test_exceptions_inherit_from_Exception
9     assert_equal __, MySpecialError.ancestors[1]
10     assert_equal __, MySpecialError.ancestors[2]
11     assert_equal __, MySpecialError.ancestors[3]
12     assert_equal __, MySpecialError.ancestors[4]
13   end
14
15   def test_rescue_clause
16     result = nil
17     begin
18       fail "Oops"
19     rescue StandardError => ex
20       result = :exception_handled
21     end
22
23     assert_equal __, result
24
25     assert_equal __, ex.is_a?(StandardError), "Should be a Standard Error"
26     assert_equal __, ex.is_a?(RuntimeError),  "Should be a Runtime Error"
27
28     assert RuntimeError.ancestors.include?(StandardError),
29       "RuntimeError is a subclass of StandardError"
30
31     assert_equal __, ex.message
32   end
33
34   def test_raising_a_particular_error
35     result = nil
36     begin
37       # 'raise' and 'fail' are synonyms
38       raise MySpecialError, "My Message"
39     rescue MySpecialError => ex
40       result = :exception_handled
41     end
42
43     assert_equal __, result
44     assert_equal __, ex.message
45   end
46
47   def test_ensure_clause
48     result = nil
49     begin
50       fail "Oops"
51     rescue StandardError => ex
52       # no code here
53     ensure
54       result = :always_run
55     end
56
57     assert_equal __, result
58   end
59
60   # Sometimes, we must know about the unknown
61   def test_asserting_an_error_is_raised
62     # A do-end is a block, a topic to explore more later
63     assert_raise(___) do
64       raise MySpecialError.new("New instances can be raised directly.")
65     end
66   end
67
68 end