Python - User-Defined Exceptions

Introduction

You can define new exceptions of your own that are specific to your programs.

User-defined exceptions are coded with classes, which inherit from a built-in exception class: usually the class named Exception:

Demo

class AlreadyGotOne(Exception): pass    # User-defined exception 
#  w  w w  . ja v  a 2  s  . c  o  m
def grail(): 
   raise AlreadyGotOne()               # Raise an instance 

try: 
     grail() 
except AlreadyGotOne:                   # Catch class name 
     print('got exception')

Result

Related Topics