DevOps | Cloud | Analytics | Open Source | Programming





How to Handle Errors and Exceptions in Python ?



In this post , we will explore How to Handle Errors and Exceptions in Python. Python errors can be Broadly of two categories -

  • Errors
  • Exceptions.
Exceptions are specific Python errors that occur when the situation being handled by the code is exceptional even though the code logic is correct. e.g. Consider division code logic below. If you try to divide something by Zero, even when your code is correct , the program will throw error. This is Exception.


x = 1
y = 0
z = x/y

  Some of the common exception types are -

  • ValueError: when an argument to a function is the right type but not in the right domain (e.g. an empty string)
  • ImportError: raised when some import fails
  • IOError: raised when some files not accessible
  • SyntaxError - raised when Python code is incorrect.
  • KeyError: raised when trying to access a key in a dictionary that does not exist
  • TypeError: raised when an argument to a function is not the correct type (e.g. a str instead of float)
  The <EXCEPTION_NAME> used in the below examples mean exceptions similar to the above - ValueError, IOError etc.   Let's see how to handle the Exceptions -  

1. Single Exception Handling :

The basic practice to handle an Exception scenario is by using a try-except code block. The basic syntax of the try-except block is -


try:
   <ANY\_BUSINESS\\MATHEMATICAL\_LOGIC\_CODE >

except <EXCEPTION\_NAME> as error:  
   print("Exception occured")

So while executing the Business Logic code block if the "except" block "exception" occurs, it executes the "except" block.  

2. Multiple Exception Handling :

If you would like to Handle Multiple Exceptions Separately that can be done with Multiple Exception block as shown below.


try:
   <ANY\_BUSINESS\\MATHEMATICAL\_LOGIC\_CODE >

except <EXCEPTION\_NAME\_1> as error:
   print("<ANYTHING\_YOU\_WANT>")

except <EXCEPTION\_NAME\_2> as error:
   print("<ANYTHING\_YOU\_WANT>")

except <EXCEPTION\_NAME\_3> as error:
   print("<ANYTHING\_YOU\_WANT>")

 

3. Generalized Exception Handling :

If you would like to have a Generalized Handling of Multiple Exceptions together that can be done as shown below. Look at the last code block for Generalized Exception Handling Approach. Note : The Order of the Exception Code Blocks are Very Important . Python follows a Top-Down Approach while executing the Exception Code Block. If Generalized Exception Handling is kept BEFORE any Specific Exception Block Handling (Unlike shown below) , then Python will ALWAYS execute ONLY the Generalized Exception Handling block.  


try:
<ANY\_BUSINESS\\MATHEMATICAL\_LOGIC\_CODE >

except <EXCEPTION\_NAME\_1> as error:
  print("<ANYTHING\_YOU\_WANT>")

except <EXCEPTION\_NAME\_2> as error:
  print("<ANYTHING\_YOU\_WANT>")

except <EXCEPTION\_NAME\_3> as error:
  print("<ANYTHING\_YOU\_WANT>")

except Exception as error: 
  print(f"An exception occurred {error}")

 

4. "Try-Finally" Exception Override Handling :

The "finally" block is executed irrespective of any kind of Exceptions . Sometimes a Clean-up or Database_Connection\File-Close activities or operations needs to be carried out MANDATORILY irrespective of Exception or No-Exceptions. Such things can be handled using the "finally" block. See example below -  


try:
  <ANY\_BUSINESS\\MATHEMATICAL\_LOGIC\_CODE >

except <EXCEPTION\_NAME\_1> as error:
  print("<ANYTHING\_YOU\_WANT>")

except <EXCEPTION\_NAME\_2> as error:
  print("<ANYTHING\_YOU\_WANT>")

except <EXCEPTION\_NAME\_3> as error:
  print("<ANYTHING\_YOU\_WANT>")

except Exception as error: 
  print(f"An exception occurred {error}")

finally:
  <Clean-up\_or\_Database\_Connection\\File-Close Activity>

 

5. "try-finally-else-except" Exception Override Handling :

We can extend the Exception handling process to add some extra  -  "else" block. The "else" block gets executed ONLY IF No exception gets caught. While the "finally" block gets executed irrespective of anything as explained in Section4.  


try: 
  <DO\_Something> 

except <EXCEPTION\_NAME> as error: 
  print("I print ONLY When this Exception occurs")

else:
  print("I Print if No Exception occurs")

finally:
  print("I print irrespective of Exception or No Exception")

 

6. User Defined Exception Handling :

User can create or define their Own Exceptions , based on Specific Business Logic, if the existing In-Bulit Python Exceptions doesn't cover the requirement or you wish to integrate some more sophisticated logging system or further inspect an object. (P.S. - More Details about Custom Exception Handling is our post - How to Code Custom Exception Handling in Python ? ) Let's say the - you have certain Business Logic which Upon not been met , a USER-DEFINED New Exception has to be raised. So first you code the Business Logic as to what EXACTLY is expected. The custom exception class inherits from the base Exception class. The __init__() method is required when defining an Exception class:


<import\_Statements> 
import os
import errno


class <Custom\_Exception\_Name>(Exception):
 
      """Exception raised for errors Custom case.
      
      Attributes:
       message -- explain about the error
      
      """

 
def \_\_init\_\_(self, message):
 
   # Calling the Base class constructor with the parameters 
   super().\_\_init\_\_(message)



 
def <Custom\_Function> () 
 
  if <CHECK\_IF\_BUSINESS\_CRITERIA\_is\_MET>
    
      <NO\_NEED\_TO\_DO\_ANYTHING>
       
  else:  ##### DEFINE THE EXCEPTION DETAILS HERE
     
      raise <Custom\_Exception\_Name>(errno.ENOENT, os.strerror(errno.ENOENT))
 
  
Custom\_Function()

 

7. Logging the Exception Handling :

It is also helpful to log the exception message sometimes for subsequent analysis process.  


import logging
 
logTheException = logging.getLogger(\_\_name\_\_)
 
def start():
 
  try:
    <ANY\_BUSINESS\\MATHEMATICAL\_LOGIC\_CODE >
 
  except <EXCEPTION\_NAME\_1> as error:
    logTheException .error(error)
    raise

  Hope this write-up on How to Handle Errors and Exceptions in Python helps.   Other Interesting Reads :

   

python exception, python try except, python try catch, python try, python raise exception, python raise, python throw exception, python keyerror, exception handling in python, python exception message, python print exception, python try except else, python catch exception, attributeerror, python custom exception, python valueerror, try and except in python, python catch all exceptions, try except else, python try finally, keyboardinterrupt, python try except finally, python print exception message, valueerror, python exception types, python catch multiple exceptions,python logging exception,python except multiple,python exception class,python try catch exception,django exceptions,nested try except python,python reraise exception, python get exception message, python, exception, python custom exception , python exception handling, python exception class, python exception traceback, python exception class, exception class python, python class exception, python custom exception, python raise custom exception, user defined exception in python, python create exception, custom exception in python,
python exception handling ,python exception handling example ,python exception handling best practices ,python exception handling programs ,python exception handling print error ,python exception handling interview questions ,python exception handling framework ,python exception handling mechanism ,python exception handling javatpoint ,python exception handling ppt ,python exception handling ,python exception message ,python exceptions ,python exception print stack trace ,python exception class ,python exception handling best practices ,python exception get message ,python exception handling programs ,python exception traceback ,python exception message string ,python handle exception ,python handle exception and continue ,python handle exception in thread ,python handle exception in list comprehension ,python handle exception in generator ,python handle exception and exit ,python handle exception and reraise ,python handle exception in function ,python handle exception gracefully ,python handle exception in context manager ,python exception handling ,python exception message ,python exceptions ,python exception print stack trace ,python exception class ,python exception handling best practices ,python exception get message ,python exception handling programs ,python exception traceback ,python exception message string ,python exception handling ,python exception message ,python exception print stack trace ,python exception class ,python exception handling best practices ,python exception get message ,python exception handling programs ,python exception traceback ,python exception message string ,python exception object attributes ,python exception handling ,python exception handling best practices ,python exception handling programs ,python exception handling print error ,python exception handling interview questions ,python exception handling framework ,python exception handling javatpoint ,python exception handling ppt ,python exception handling keywords ,python exception handling w3schools