Programming with Python

  1. Home
  2. Docs
  3. Programming with Python
  4. Exception handling in python
  5. User defined Exception

User defined Exception

Errors and exceptions are similar but different terms.

While error represents, any bug in the code that disrupt running of the program or cause improved output.

An exception refers to any irregular situation occurring during run time, which we have no control on.

Errors in a program can be fixed by making corrections in the code, fixing exceptions is not that simple.

Exception in a program as a situation that occurs during runtime and programmer has no control on it.

A good program is one that has a code that handles an exception well i.e., in case an exception occurs, then the exception handling code written for it, will take over and do the necessary action.

Exception handling in python involves the use of try and except clauses wherein the code that may generate an exception is written in the try block and the code for handling the exception when the exception is raised, written in except block.

There are many built-in exceptions in python. But sometimes we have to make our own custom exception class to serve our purpose.

Users can define custom exceptions by creating a new class, in python.

e.g.,

class error(RuntimeError):
   def __init__(self, a):
      self.args = a
try:
   raise error("UserError")
except error as r:
   print (r.args)
Output- 
('U','s','e','r','e','r','r','o','r')

In this article, we learnt how we declare and implement user-defined exceptions in Python 3.x.

Was this article helpful to you? Yes No

How can we help?