Get up to 80 % extra points for free! More info:

Discussion: User-defined Exceptions

Activities
Avatar
Rahul Sharma
Member
Avatar
Rahul Sharma:12/30/2021 2:19

Programs may name their own exceptions by creating a new exception class . Exceptions should typically be derived from the Exception class, either directly or indirectly.

Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception. When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:

class Error(Exception):
"""Base class for exceptions in this module."""
pass

class InputError(Error):
"""Exception raised for errors in the input.

Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""

def __init__(self, expression, message):
self.expression = expression
self.message = message

class TransitionError(E­rror):
"""Raised when an operation attempts a state transition that's not
allowed.

Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""

def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions.

Reply
12/30/2021 2:19
Get the Best Python Course in Pune - https://voticle.com/a/articles/222976/python-job-opportunities-for-freshers
Avatar
tariqyoshi
Member
Avatar
tariqyoshi:8/25/2023 5:27

User-defined exceptions are also referred to as custom exceptions. The exceptions created per our use case and thrown using the throw keyword are user-defined exceptions, and such exceptions are derived classes of the Exception class from the java.

 
Up Reply
8/25/2023 5:27
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

2 messages from 2 displayed.