Search notes:

Python: try

Demo

for i in range (-7, 7):

    try:
       print(f'1000 / {i} = {1000/i}')

    except ZeroDivisionError:
       print("i is zero, division impossible")
Github repository about-python, path: /statements/try/demo.py

User defined exceptions

By deriving a class from an exception class (such as BaseException), it is possible to create a user defined exception that can be thrown and caught:
class SomethingIsWrong(BaseException):

      def __init__(self, reason):
          self.reason = reason

      def __str__(self):
          return self.reason


try:
   print('one')
   raise SomethingIsWrong('xyz')
   print('two')

except SomethingIsWrong as somethingWrong:
    print(f'Exception caught: {str(somethingWrong)}')

Github repository about-Python, path: /statements/try/user-defined-exception.py
Note that Python's documentation recommends to derive from Exception rather than from BaseException.

See also

The else clause
exception handling

Index