Exception Handling

journey into python

Helpful links

What is exception handling in Python?

Exceptions can be handled in Python using a try block. The operation that may produce an exception is placed within the try statement. The code that handles the exceptions is contained within the except clause. We have direct control over which operations to perform after catching the exception.

What is the difference between error and exception handling in Python?

Errors can be caused by incorrect coding, hardware failures, or unexpected inputs. Exceptions occur during the execution of a program that disrupts the normal flow of instructions. When an exception occurs, it causes the current process to stop and generates an error message. Exception handling is a mechanism for dealing with exceptions. It is used to prevent errors from crashing a program and to clean up any resources that have been allocated. Error handling is the process of detecting and correcting errors, while exception handling is dealing with exceptions that occur in a program.

Python provides two ways to handle errors: try/except and error handling. The try/except statement allows you to catch exceptions that occur in your code. The error handling mechanism will enable you to handle errors in your code without crashing the program. Both of these methods are important for robust programming in Python.

What are the benefits of exception handling?

Exception handling is a mechanism for dealing with exceptions. It is used to prevent errors from crashing a program and to clean up any resources that have been allocated. Exception handling is an integral part of robust programming in Python.

The benefits of exception handling are:

  • Prevents crashes: If an exception is not handled, it can cause a program to crash. Exception handling prevents this from happening.
  • Cleans up resources: When an exception occurs, it can leave behind resources that are no longer needed. Exception handling helps clean up these resources so that they can be reused.
  • Makes code more readable: Code that uses exception handling is more readable than code that doesn’t. This is because exception handling clarifies what is supposed to happen when an exception occurs.
  • Makes code easier to maintain: Code that uses exception handling is easier to maintain than code that doesn’t. This is because exception handling makes it easy to add new Exception types without modifying the existing code.

Exception handling is a powerful tool that can improve the quality of your code. When used correctly, it can help prevent crashes and make your code more readable and maintainable.

Simple exception handling example in Python

Consider the following simple example where we open a file and read its contents. If the file does not exist, we want to print an error message.

try:
  f = open("test.txt",encoding = 'utf-8')
except FileNotFoundError:
  print("File does not exist")
File does not exist

If the file test.txt exists, then the file’s contents will be printed. If the file does not exist, an error message saying that the file does not exist will be printed.

Multiple exceptions

try:
  f = open("test.txt",encoding = 'utf-8')
except FileNotFoundError:
  print("File does not exist")
except LookupError:
  print("Encoding is not correct")
except UnicodeDecodeError:
  print("The file is not encoded in utf-8")
File does not exist

If the file test.txt exists, then the file’s contents will be printed. If the file does not exist, an error message saying that the file does not exist will be printed. Similarly, if the encoding is incorrect or the file is not encoded in utf-8, then appropriate error messages will be printed.

Multiple exceptions in one except clause

We can also have multiple exceptions in one except clause. For example,

try:
  f = open("test.txt",encoding = 'utf-8')
except (FileNotFoundError, LookupError, UnicodeDecodeError):
  print("Something went wrong")
Something went wrong

Here, if any of the three exceptions (FileNotFoundError, LookupError, UnicodeDecodeError) occur, then the print statement inside the except clause will be executed.

Raising an exception

We can also raise an exception using the raise statement. For example,

try:
  f = open("test.txt",encoding = 'utf-8')
except FileNotFoundError:
  raise Exception("File does not exist")
---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

 in ()
      1 try:
----> 2   f = open("test.txt",encoding = 'utf-8')
      3 except FileNotFoundError:

FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

During handling of the above exception, another exception occurred:

Exception                                 Traceback (most recent call last)

 in ()
      2   f = open("test.txt",encoding = 'utf-8')
      3 except FileNotFoundError:
----> 4   raise Exception("File does not exist")

Exception: File does not exist

If the file test.txt does not exist, then an exception will be raised with the message “File does not exist”. Note that you can also raise any other exception instead of the Exception class.

Creating custom exceptions

We can also create custom exceptions by creating a new class inherited from the Exception class. For example,

class MyError(Exception):
  def __init__(self, value):
    self.value = value

def __str__(self):
  return repr(self.value)

try:
  raise MyError(2*2)
except MyError as e:
  print('My exception occurred, value:', e.value)
My exception occurred, value: 4
In this code, we create a new class called MyError, inheriting from the Exception class. We then raise an exception of this type with the value 4. When we catch this exception, we print the value of the exception (4).
  File "", line 1
    In this code, we create a new class called MyError, inheriting from the Exception class. We then raise an exception of this type with the value 4. When we catch this exception, we print the value of the exception (4).
          ^
SyntaxError: invalid syntax

What is the difference between raising an error and throwing an exception in Python?

The main difference between raising an error and throwing an exception in Python is that it is displayed to the user when we raise an error, while when we throw an exception, it is not displayed to the user. Raising an error is used to notify the user about an exceptional condition, while throwing an exception transfers the control from one part of the code to another.

Finally clause

We can also use a finally clause to execute code regardless of whether or not an exception occurs. For example,

try:
  f = open("test.txt",encoding = 'utf-8')
except FileNotFoundError:
  print("File does not exist")
finally:
  print("This code will always be executed")
File does not exist
This code will always be executed

If an exception occurs, the code inside the except clause will be executed. If no exception occurs, then the code inside the finally clause will be executed.

Can you use a try without an except?

No. Because we cannot have the try block without except, we can only attempt to ignore the exception in order for the code not to go into the except block and include a pass statement in the exception.

try:
  print(1/0)
except:
  pass

The pass statement is used as a placeholder and does nothing. We can also use it to ignore an exception.

How do you suppress warnings in Python?

In Python, warnings are generated when outdated classes, functions, keywords, and so on are utilized. These aren’t the same as mistakes. When a program terminates due to an error, it does so immediately. However, if there are warnings in the program, it continues to execute.
The warnings module handles warnings in Python. We can show warnings raised by the user with the warn() function. We can use the filterwarnings() function to perform actions on specific warnings.

import warnings
warnings.filterwarnings("ignore")

Leave a Comment