A Comprehensive Guide to Exception Handling in Python

Exception handling is a mechanism in Python that deals with runtime errors, allowing the program to continue execution or handle errors gracefully. It is an essential tool for making Python applications robust and error-resistant.

Definition

An exception is an event that arises during a program’s execution, interrupting its regular flow. When an error occurs in a Python script, it triggers an exception, which can be managed to prevent the program from crashing (stopping).

Advantages of Exception Handling

  1. Improved Code Readability: It allows errors to be handled cleanly.
  2. Program Continuity: Exceptions enable programs to continue running even after encountering an error.
  3. Error Logging: Helps diagnose the issue by capturing specific error details.
  4. Separation of Error Handling Logic: Keeps normal code separate from error-handling logic.
  5. Graceful Termination: Programs can terminate gracefully instead of crashing abruptly.

Two types of errors in a programming language

  1. Syntax error
  2. Runtime error

Syntax Error:

Syntax errors occurs when the code breaks or violates the rules or structure of the programming language. These errors are detected before the program runs, during the compilation or interpretation phase. The program cannot execute until the syntax error is fixed.

Example:

print("Hello World"  # Missing closing parenthesis

Explanation: In the above example, the closing parenthesis is missing, which results in a syntax error. The program will not run and will raise an error like:

SyntaxError: unexpected EOF while parsing

Note: A programmer must correct all syntax errors before executing the program.

Runtime Errors:

Runtime errors occurs during the execution of the program. These errors happen after the program has started executing and typically arise due to unexpected operations (e.g., division by zero, invalid operations on data types, programmer logic, memory problems, or end-user input… ).

Example:

x = 10 / 0  # Division by zero

Explanation: Here, the program will start executing but will break at the point where the division done by zero occurs. This will result in a runtime error like:

ZeroDivisionError: division by zero

Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors.

Exception hierarchy diagram

image 5 Explore and Read Our Blogs Written By Our Insutry Experts Learn From KSR Data Vizon

Most commonly encounter error are

Error TypeDescriptionExample
SyntaxErrorOccurs when the Python parser detects a syntax error.x = 10
print(x) # Missing a colon in function or if statement
IndentationErrorRaised when there is incorrect indentation in the code.def my_function():
print(“Hello”) # Expected indentation block
TypeErrorRaised when an operation or function is applied to an object of inappropriate type.result = “2” + 2
# Trying to add a string and an integer
ValueErrorRaised when a function receives an argument of the right type but inappropriate value.int(“abc”)
# Converting a string to integer when it’s not a valid number
NameErrorRaised when a local or global name is not found.print(age) # Trying to use a variable that hasn’t been defined
ZeroDivisionErrorRaised when attempting to divide by zero.result = 10 / 0
# Division by zero error
IndexErrorRaised when trying to access an index that is out of range in a sequence (e.g., list, tuple).my_list = [1, 2, 3]
print(my_list[5])
# Accessing an index that doesn’t exist
KeyErrorRaised when trying to access a dictionary with a key that doesn’t exist.my_dict = {“name”: “Alex”}
print(my_dict[“age”])
# Accessing a nonexistent key
AttributeErrorRaised when an invalid attribute reference or assignment occurs.x = 5
x.append(10)
# Trying to use a list method on an integer
ModuleNotFoundErrorRaised when attempting to import a module that cannot be found.import nonexistent_module
# Trying to import a module that doesn’t exist
FileNotFoundErrorRaised when trying to open a file that does not exist.with open(“nonexistent_file.txt”, “r”) as file:
data = file.read() # Trying to read a file that doesn’t exist
OverflowErrorRaised when the result of an arithmetic operation is too large to be represented.import math math.exp(1000) # Exceeding the maximum value representable by a float
ImportErrorRaised when an import statement fails to find the module definition or when an imported object cannot be retrieved.from math import non_existent_function # Trying to import a non-existent function from a module

Types of Exceptions with Syntax:

1. try-except block:

try:
    # code that may raise an exception
except <ExceptionType>:
    # code to execute if the exception is raised

2. try with multiple except blocks:

try:
    # code that may raise an exception
except <ExceptionType>: # ZeroDivisionError
    # code to handle the exception
except <ExceptionType>: #ValueError
    # code to handle the exception
else:
    # code to execute if no exception was raised

3. Single except block can handle multiple exceptions:

try:
     # code that may raise an exception
except (Exception1,Exception2,exception3,..):
     # code that may raise an exception
                   # (OR)
except (Exception1,Exception2,exception3,..) as msg:
     # code that may raise an exception

Note: The following are different possible variations of except blocks.

  1. except ZeroDivisionError:
  2. except ZeroDivisionError as msg:
  3. except (ZeroDivisionError, ValueError) :
  4. except (ZeroDivisionError, ValueError) as msg:
  5. except :

4. try-except-else block:

try:
    # code that may raise an exception
except <ExceptionType>:
    # code to handle the exception
else:
    # code to execute if no exception was raised

5. try-except-finally block:

try:
    # code that may raise an exception
except <ExceptionType>:
    # code to handle the exception
finally:
    # code that will always execute, regardless of exceptions

6. Raise exception:

raise <ExceptionType>('error message')

7. Custom Exceptions:

class CustomError(Exception):
    pass

Examples:

Basic try-except:

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")

try with multiple except blocks:

try:
      x=int(input("Enter First Number: "))
      y=int(input("Enter Second Number: "))
      print(x/y)
except ZeroDivisionError:
      print("Can't Divide with Zero")
except ValueError:
      print("please provide int value only")

Single except block can handle multiple exceptions:

try:
     x=int(input("Enter First Number: "))
     y=int(input("Enter Second Number: ")) 
     print(x/y)
except (ZeroDivisionError, ValueError) as z:
      print("Please Provide valid numbers only and problem is: ", z)

try-except-else-finally:

try:
    result = 10 / 5
except ZeroDivisionError:
    print("Division by zero!")
else:
    print("Result:", result)
finally:
    print("This block always executes.")

Raising a Custom Exception:

class InvalidAgeError(Exception):
    def __init__(self, age):
        self.age = age

def validate_age(age):
    if age < 18:
        raise InvalidAgeError("Age is less than 18.")

try:
    validate_age(15)
except InvalidAgeError as e:
    print(e)

Conclusion

Exception handling in Python ensures that errors are managed effectively without disrupting program execution. By handling errors using try-except blocks and creating custom exceptions, Python developers can write more robust, maintainable code.

Knowledge Check

Related Article No.4

https://blog.ksrdatavision.com/python/input-and-output-in-python
Data Analytics with Power Bi and Fabric
Could Data Engineer
Data Analytics With Power Bi Fabic
AWS Data Engineering with Snowflake
Azure Data Engineering
Azure & Fabric for Power bi
Full Stack Power Bi
Subscribe to our channel & Don’t miss any update on trending technologies

Kick Start Your Career With Our Data Job

Master Fullstack Power BI – SQL, Power BI, Azure Cloud & Fabric Tools
Master in Data Science With Generative AI Transform Data into Business Solutions
Master Azure Data Engineering – Build Scalable Solutions for Big Data
Master AWS Data Engineering with Snowflake: Build Scalable Data Solutions
Transform Your Productivity With Low Code Technology: Master the Microsoft Power Platform

Social Media channels

► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizo

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *