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 
# from  w ww.  j  a va 2s . co  m
def grail(): 
   raise AlreadyGotOne()               # Raise an instance 

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

Result

Related Topics