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):
   pass

class OSFileNotFoundError(Exception):
   pass

try:
os.scandir()
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()
else:
   raise

You can do this:

try:
os.scandir()
except OSError as error:
   if error.errno in (errno.EACCES, errno.EPERM): #Permission denied
handle_permission_error()
elif error.errno == errno.ENOENT: #File not found
handle_FileNotFoundError_error()
else:
   raise

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
try:
...
except SomeException:
   tb = sys.exc_info()[2]
raise OtherException(...).with_traceback(tb)
BaseException
   +
   --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 +
   --ResourceWarning

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):
   ...pass
   ...

   >>>
   raise CustomError
Traceback(most recent call last):
   ...
   __main__.CustomError

   >>>
   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"
""
pass

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

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

# you need to guess this number
number = 10

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

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.

Output

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.

Attributes:
   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
super().__init__(self.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:

try:
# do something

except ValueError:
   # handle ValueError exception

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

except:
   # handle all other exceptions

finally:
# cleanup resources
2._
#!/usr/bin/env python

# zero_division.py

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/simple.py", 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.

$. / zero_division2.py
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
6._
#!/usr/bin/env python

# zerodivision3.py

def input_numbers():

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

x, y = input_numbers()

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

except ZeroDivisionError:

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