In Python, an exception is an event that occurs during the execution of a program and disrupts its normal flow. Exception handling is an essential part of robust software development. Python provides powerful tools to handle exceptions gracefully and ensure programs continue or terminate cleanly without crashing abruptly.
This document covers various aspects of Python exceptions including built-in exceptions, custom exceptions, the try-except block, else and finally clauses, nested exceptions, exception propagation, exception hierarchy, and best practices.
An exception is an error that occurs at runtime, not at compilation. When an error occurs, Python creates an object representing that error and stops the current execution flow unless handled explicitly. If not handled, the program crashes and displays an error traceback.
print(10 / 0) # Raises ZeroDivisionError
Detected at compile-time (before execution). These are errors in code syntax.
if True
print("Missing colon")
These occur during execution. Python stops execution and raises an exception object.
int("abc") # Raises ValueError
try:
# Code that might raise an exception
except ExceptionType:
# Handling code
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
try:
num = int(input("Enter a number: "))
result = 100 / num
except ValueError:
print("Invalid input, not an integer.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
The else block is executed if no exception is raised.
try:
value = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print("Valid input:", value)
The finally block always executes, whether an exception is raised or not. It's useful for cleanup actions like closing files or releasing resources.
try:
file = open("demo.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
print("Executing finally block")
if 'file' in locals():
file.close()
try:
try:
print(10 / 0)
except ZeroDivisionError:
print("Handled inner division error.")
except:
print("Handled outer error.")
You can raise exceptions manually using the raise keyword.
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print("Age is valid.")
set_age(-5) # Raises ValueError
Built-in exceptions may not cover all error scenarios in your application. Custom exceptions let you define application-specific errors.
class MyCustomError(Exception):
pass
raise MyCustomError("A custom error occurred")
class InvalidInputError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
try:
raise InvalidInputError("Invalid input provided!")
except InvalidInputError as e:
print("Error:", e.message)
try:
1 / 0
except ZeroDivisionError as e:
print("Exception:", e)
import sys
try:
raise ValueError("Invalid value!")
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
print("Type:", exc_type)
print("Value:", exc_value)
try:
raise KeyError("Key missing")
except KeyError as e:
raise ValueError("Incorrect value") from e
from contextlib import suppress
with suppress(FileNotFoundError):
open("missing_file.txt")
import logging
logging.basicConfig(filename="error.log", level=logging.ERROR)
try:
1 / 0
except ZeroDivisionError as e:
logging.error("Exception occurred", exc_info=True)
def read_file(file_name):
try:
with open(file_name, "r") as f:
return f.read()
except FileNotFoundError:
return "File not found."
except IOError:
return "I/O error occurred"
def get_positive_number():
while True:
try:
num = int(input("Enter a positive number: "))
if num <= 0:
raise ValueError("Number must be positive.")
return num
except ValueError as e:
print("Error:", e)
print("You entered:", get_positive_number())
Exception handling in Python is a powerful feature that allows developers to handle unexpected situations gracefully and ensure program stability. By understanding how to use try-except blocks, else and finally clauses, raise custom exceptions, and follow best practices, you can write more robust and maintainable Python code.
Proper exception management not only improves code readability but also aids in debugging, error logging, and better application design. With great tools and flexibility offered by Pythonβs exception framework, mastering this area is essential for any serious Python developer.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved