python user-defined exceptions to handle specific oserror codes

  • Last Update :
  • Techknowledgy :

There are a large number of possible errors that could be part of the OSError. You can use these to raise your own custom exceptions and then handle them further up the stack.

class OSPermissionError(Exception):

class OSFileNotFoundError(Exception):

except OSError as error:
   # Not found
if error.errno == errno.ENOENT:
   raise OSFileNotFoundError()
# Permissions Error
elif error.errno in [errno.EPERM, errno.EACCES]:
   raise OSPermissionError()

You can do this:

except OSError as error:
   if error.errno in (errno.EACCES, errno.EPERM): #Permission denied
elif error.errno == errno.ENOENT: #File not found

Suggestion : 2

Last Updated : 08 Jun, 2022

Output : 

OSError: [Errno 25] Inappropriate ioctl
for device

Suggestion : 3

User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition “just like” the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error.,Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.,Raised when a generator or coroutine is closed; see generator.close() and coroutine.close(). It directly inherits from BaseException instead of Exception since it is technically not an error.,When a generator or coroutine function returns, a new StopIteration instance is raised, and the value returned by the function is used as the value parameter to the constructor of the exception.

raise new_exc from original_exc
except SomeException:
   tb = sys.exc_info()[2]
raise OtherException(...).with_traceback(tb)
   --SystemExit +
   --KeyboardInterrupt +
   --GeneratorExit +
   --Exception +
   --StopIteration +
   --StopAsyncIteration +
   --ArithmeticError |
   + --FloatingPointError |
   + --OverflowError |
   + --ZeroDivisionError +
   --AssertionError +
   --AttributeError +
   --BufferError +
   --EOFError +
   --ImportError |
   + --ModuleNotFoundError +
   --LookupError |
   + --IndexError |
   + --KeyError +
   --MemoryError +
   --NameError |
   + --UnboundLocalError +
   --OSError |
   + --BlockingIOError |
   + --ChildProcessError |
   + --ConnectionError |
   | + --BrokenPipeError |
   | + --ConnectionAbortedError |
   | + --ConnectionRefusedError |
   | + --ConnectionResetError |
   + --FileExistsError |
   + --FileNotFoundError |
   + --InterruptedError |
   + --IsADirectoryError |
   + --NotADirectoryError |
   + --PermissionError |
   + --ProcessLookupError |
   + --TimeoutError +
   --ReferenceError +
   --RuntimeError |
   + --NotImplementedError |
   + --RecursionError +
   --SyntaxError |
   + --IndentationError |
   + --TabError +
   --SystemError +
   --TypeError +
   --ValueError |
   + --UnicodeError |
   + --UnicodeDecodeError |
   + --UnicodeEncodeError |
   + --UnicodeTranslateError +
   --Warning +
   --DeprecationWarning +
   --PendingDeprecationWarning +
   --RuntimeWarning +
   --SyntaxWarning +
   --UserWarning +
   --FutureWarning +
   --ImportWarning +
   --UnicodeWarning +
   --BytesWarning +
   --EncodingWarning +

Suggestion : 4

In this tutorial, you will learn how to define custom exceptions depending upon your requirements with the help of examples.,In this example, we will illustrate how user-defined exceptions can be used in a program to raise and catch errors.,Here, we have overridden the constructor of the Exception class to accept our own custom arguments salary and message. Then, the constructor of the parent Exception class is called manually with the self.message argument using super().,Here, we have created a user-defined exception called CustomError which inherits from the Exception class. This new exception, like other exceptions, can be raised using the raise statement with an optional error message.

In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.

>>> class CustomError(Exception):

   raise CustomError
Traceback(most recent call last):

   raise CustomError("An error occurred")
Traceback(most recent call last):
   __main__.CustomError: An error occurred

This program will ask the user to enter a number until they guess a stored number correctly. To help them figure it out, a hint is provided whether their guess is greater than or less than the stored number.

# define Python user - defined exceptions
class Error(Exception):
"Base class for other exceptions"

class ValueTooSmallError(Error):
"Raised when the input value is too small"

class ValueTooLargeError(Error):
"Raised when the input value is too large"

# you need to guess this number
number = 10

# user guesses a number until he / she gets it right
while True:
   i_num = int(input("Enter a number: "))
if i_num < number:
   raise ValueTooSmallError
elif i_num > number:
   raise ValueTooLargeError
except ValueTooSmallError:
   print("This value is too small, try again!")
except ValueTooLargeError:
   print("This value is too large, try again!")

print("Congratulations! You guessed it correctly.")

Here is a sample run of this program.

Enter a number: 12
This value is too large,
try again!

   Enter a number: 0
This value is too small,
try again!

   Enter a number: 8
This value is too small,
try again!

   Enter a number: 10
Congratulations!You guessed it correctly.


Enter salary amount: 2000
Traceback (most recent call last):
File "<string>", line 17, in <module>
      raise SalaryNotInRangeError(salary)
      __main__.SalaryNotInRangeError: Salary is not in (5000, 15000) range

We can also customize the __str__ method itself by overriding it.

class SalaryNotInRangeError(Exception):
"Exception raised for errors in the input salary.

   salary--input salary which caused the error
message--explanation of the error ""

def __init__(self, salary, message = "Salary is not in (5000, 15000) range"):
   self.salary = salary
self.message = message

def __str__(self):
   return f '{self.salary} -> {self.message}'

salary = int(input("Enter salary amount: "))
if not 5000 < salary < 15000:
   raise SalaryNotInRangeError(salary)

Suggestion : 5

last modified December 15, 2021

In Python, we have the following syntax to deal with exceptions:

# do something

except ValueError:
   # handle ValueError exception

except(IndexError, ZeroDivisionError):
   # handle multiple exceptions
# IndexError and ZeroDivisionError

   # handle all other exceptions

# cleanup resources
#!/usr/bin/env python


def input_numbers():

   a = float(input("Enter first number:"))
b = float(input("Enter second number:"))
return a, b

x, y = input_numbers()
print(f "{x} / {y} is {x/y}")

In this script, we get two numbers from the console. We divide these two numbers. If the second number is zero, we get an exception.

Enter first number:3
Enter second number:0
Traceback (most recent call last):
    File "C:/Users/Jano/PycharmProjects/Simple/", line 14, in <module>
    print(f"{x} / {y} is {x/y}")
ZeroDivisionError: float division by zero

First, we simply check that y value is not zero. If the y value is zero, we print a warning message and repeat the input cycle again. This way we handled the error and the script is not interrupted.

$. /
Enter first number: 4
Enter second number: 0
Cannot divide by zero
Enter first number: 5
Enter second number: 0
Cannot divide by zero
Enter first number: 5
Enter second number: 6
5.0 / 6.0 is 0.8333333333333334
#!/usr/bin/env python


def input_numbers():

   a = float(input("Enter first number:"))
b = float(input("Enter second number:"))
return a, b

x, y = input_numbers()

print(f "{x} / {y} is {x/y}")

except ZeroDivisionError:

   print("Cannot divide by zero")
x, y = input_numbers()