DEV Community

seng
seng

Posted on

Class Exception and Its Subclasses in Python

Class Exception and Its Subclasses

Used in begin…end blocks with rescue and in Kernel#raise.

Exception objects carry information about the exception:

  • Its type (the class of the exception).
  • An optional descriptive message.
  • Optional backtrace information.
  • Some built-in subclasses of Exception have additional methods: for example, NameError#name.

Default Exception Classes

Two Ruby statements have default exception classes:

  • raise: Defaults to RuntimeError.
  • rescue: Defaults to StandardError.

When an exception has been raised but not yet handled (in rescue, ensure, at_exit, and END blocks), two global variables are set:

  • $! contains the current exception.
  • $@ contains its backtrace.
#!/usr/bin/ruby 
#encoding:UTF-8
x=100
begin
   result=x/0
rescue Exception=>err
   puts "Error: #{err}" 
   puts "Current exception: #{$!}" 
   puts "Backtrace: #{$@}"
ensure 
   puts "Division operation ended"
end
Enter fullscreen mode Exit fullscreen mode
#!/usr/bin/ruby 
#encoding:UTF-8
x=100
begin
   result=x/0
rescue StandardError=>err
   puts "Error: #{err}" 
   puts "Current exception: #{$!}" 
   puts "Backtrace: #{$@}"
ensure 
   puts "Division operation ended"
end
Enter fullscreen mode Exit fullscreen mode

Output:

Error: divided by 0
Current exception: divided by 0
Backtrace: ["learn4.rb:5:in `/'", "learn4.rb:5:in `<main>'"]
Division operation ended
Enter fullscreen mode Exit fullscreen mode

Custom Exception Classes

To provide additional or alternative information, programs can create custom exception classes derived from built-in exception classes.

#!/usr/bin/ruby 
#encoding:UTF-8

class Score
       class Error < ::StandardError
            def initialize()
                 @message = "Score value is abnormal"
            end 
            def sayErr()
                puts @message
            end     
       end 
end

puts "Please enter the score:"
score=gets.chomp.to_i
begin
   case score
        when 0...60 
             puts "Fail"
        when 61..80
             puts "Good"
        when 81..99
             puts "Excellent"
        when 100
             puts "Perfect score"
        else
             raise Score::Error.new
   end
rescue Score::Error=>err
        err.sayErr()
ensure 
       puts "Thank you for entering the score"
end
Enter fullscreen mode Exit fullscreen mode

Example execution:

Please enter the score:
1124
Score value is abnormal
Thank you for entering the score

Please enter the score:
99 
Excellent
Thank you for entering the score
Enter fullscreen mode Exit fullscreen mode

A good practice is for a library to create a "general" exception class (usually a subclass of StandardError or RuntimeError) and have its other exception classes derive from it. This allows users to rescue the general exception, thereby catching all exceptions the library might raise, even if future versions of the library add new exception subclasses.

Built-in subclasses of Exception include:

  • NoMemoryError
  • ScriptError
    • LoadError
    • NotImplementedError
    • SyntaxError
  • SecurityError
  • SignalException
    • Interrupt
  • StandardError
    • ArgumentError
      • UncaughtThrowError
    • EncodingError
    • FiberError
    • IOError
      • EOFError
    • IndexError
      • KeyError
      • StopIteration
        • ClosedQueueError
    • LocalJumpError
    • NameError
      • NoMethodError
    • RangeError
      • FloatDomainError
    • RegexpError
    • RuntimeError
      • FrozenError
    • SystemCallError
      • Errno::*
    • ThreadError
    • TypeError
    • ZeroDivisionError
  • SystemExit
  • SystemStackError
  • fatal

Top comments (0)