Python Custom Exceptions

1) Define & Raise Basic Custom Exception

Define a custom exception class MyError and raise it unconditionally.


2) Raise on Negative Input

Ask user for a number; if it’s negative, raise NegativeError(Exception) with message "Negative not allowed".


3) Handle Custom Exception

Wrap the input logic from #2 in try/except and catch your NegativeError, printing its message.


4) Custom Exception Class With Message

Define a custom exception AgeError that prints "Age must be between 0 and 120" when raised.


5) Validate Age Input

Ask user for age. If age < 0 or > 120, raise and catch AgeError.


6) Custom Exception in Function

Write:

Raise DivideByZeroError if b == 0; otherwise return result.


7) Custom Exception for Even Input

Ask user for a number; if it’s even, raise EvenNotAllowedError, else print odd number.


8) Custom Exception in Loop

Loop asking for 3 integers; if any is negative, raise and catch NegativeError but continue the loop.


9) Raise on Empty String

Ask for a string; if it’s empty (""), raise EmptyStringError.


10) File Name Check

Ask for a filename; if it doesn’t end in .txt, raise InvalidFileError.


11) Custom Exception Hierarchy

Define a base class InputError(Exception), then subclass it with TooSmallError and TooLargeError.

Use them for input validation.


12) Dictionary Key Check

Ask for a key in {"a":1}; if key not found, raise KeyMissingError.


13) Value Range Check

Ask for a number 1–10; if outside range, raise OutOfRangeError.


14) Raise in Class Method

Define a class Person with method:

Raise AgeError if invalid.


15) Raise & Pass Message

Raise a custom exception with a dynamic message (include the bad value).

Example:


16) Catch All Custom Errors

Group multiple custom exceptions under one except using a tuple.


17) Safe List Access

Ask for an index; if out of bounds, raise and catch IndexTooLargeError.


18) Validate Non-Numeric Input

Ask for a number; if input contains letters, raise NotNumericError.


19) Custom Exception with Attributes

Define a custom exception with an extra attribute code. Raise it and print both message and code.


20) Re-raising Exception

In a function, catch a built-in exception (e.g., ValueError) and re-raise it as your custom exception.


🧩 Concepts Practiced

Focus
What You Learn

Defining custom exceptions

class MyError(Exception)

Raising exceptions

raise MyError("msg")

Catching custom errors

except MyError:

Dynamic messages

include values in exception text

Exception inheritance

base and subclass exceptions

Re-raising exceptions

translate built-ins to custom


📌 Starter Template

Here’s a minimal custom exception you can reuse:

Handling it:


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated