Exception Handling in Python: A Comprehensive Guide
·4 mins·
Author
Hisam Mehboob
metaphysically displaced person
Table of ContentsTable of Contents
Exception handling is a crucial aspect of writing robust and reliable Python code. Whether you’re a beginner or an experienced developer, getting an error, or exception, in your Python program means the entire program will crash. You don’t want this to happen in real-world programs. Instead, you want the program to detect errors, handle them, and then continue to run. In this blog, we’ll explore the fundamentals of exception handling in Python, including syntax, best practices, and advanced techniques.
Exceptions are runtime errors that disrupt the normal flow of a program. For example, trying to open a non-existent file, dividing by zero, or accessing an invalid index in a list will raise exceptions. If unhandled, these exceptions cause your program to crash.
The primary mechanism for handling exceptions in Python is the try-except block. Errors can be handled with with this. The code that could potentially have an error is put in a try clause. The program execution moves to the start of a following except clause if an error happens.
Here’s the basic structure:
defcal(value):try:return10/valueexceptZeroDivisionError:print("Cannot divide by zero!")print(cal(0))print(cal(2))print(cal(3))
Always catch specific exceptions to avoid silencing unexpected errors. Python has many built-in exceptions (e.g., ValueError, TypeError, FileNotFoundError).
importmathx=int(input('Please enter a positive number: '))try:print(f'Square Root of {x} is {math.sqrt(x)}')exceptValueError:print('Number is less than 0')
The else block runs only if no exceptions were raised in the try block. Use it to separate “happy path” code from error handling.
importmathdefsqr(value):try:x=math.sqrt(value)exceptValueError:print('Number is less than 0')else:print(f'The Answer is: {x}')value=int(input('Please enter a positive number: '))sqr(value)
The finally block runs regardless of whether an exception occurred. It’s ideal for cleanup tasks (e.g., closing files or releasing resources).
importmathdefsqr(value):try:x=math.sqrt(value)exceptValueError:print('Error')else:print(f'The Answer is: {x}')finally:print('Program Ends')value=int(input('Please enter a positive number: '))sqr(value)
Define custom exceptions by subclassing Python’s built-in Exception class. This makes your code more readable and errors more descriptive. (note: I have used RegEx, for that blog will be out soon :) )
importreclassInvalidEmailError(Exception):"""Raised when an email format is invalid."""passdefsend_email(valid,email):ifnotvalid:raiseInvalidEmailError(f"Invalid email: {email}")email=input('Please enter your email: ')valid=re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',email)try:send_email(valid,email)exceptInvalidEmailErrorase:print(e)
We can Log an exception in Python with an error. This can be done in the logging.exception() method. This function logs a message with level ERROR on this logger.
importmathimportloggingdefsqr(value):try:x=math.sqrt(value)exceptValueError:logging.exception("Error")else:print(f'The Answer is: {x}')finally:print('Program Ends')value=int(input('Please enter a positive number: '))sqr(value)
Exception handling is essential for writing better Python applications. By using try-except blocks effectively, catching specific errors, and with else/finally clauses, you can create programs that handle unexpected scenarios.