Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
Exception handling is the process of detecting and responding to errors and exceptional situations in software programs. In Python, exceptions are raised when an error or exceptional situation occurs, and can be caught and handled using a try
-except
block.
Some common exception types in Python include:
SyntaxError
: Raised when there is a syntax error in the code.TypeError
: Raised when an operation or function is applied to an object of inappropriate type.ValueError
: Raised when an operation or function receives an argument of the correct type but an inappropriate value.ZeroDivisionError
: Raised when a division or modulo operation is attempted with a divisor of zero.FileNotFoundError
: Raised when a file or directory cannot be found.IndexError
: Raised when an index is out of range.Here's an example of a try
-except
block that catches a ValueError
exception:
try: x = int(input("Enter a number: ")) if x < 0: raise ValueError("Negative numbers are not allowed") except ValueError as ex: print("Error:", ex)
In this example, we use a try
block to get an integer input from the user using the input()
function and convert it to an integer using the int()
function. If the input is negative, we raise a ValueError
exception with a custom error message using the raise
statement. We catch the exception in the except
block using the as
keyword to assign the exception object to a variable called ex
, and print an error message.
When this code is executed, if the user enters a negative number, the output will be:
Enter a number: -5 Error: Negative numbers are not allowed
If the user enters a positive number, the code will execute without any exceptions.
In summary, exception handling is the process of detecting and responding to errors and exceptional situations in software programs. In Python, exceptions are raised when an error or exceptional situation occurs, and can be caught and handled using a try
-except
block. There are many different types of exceptions in Python, including SyntaxError
, TypeError
, ValueError
, ZeroDivisionError
, FileNotFoundError
, and IndexError
, among others.
How does exception handling work in Python?
try
, except
, else
, and finally
blocks to manage runtime errors gracefully.try: # Code that may raise an exception result = 10 / 0 except ZeroDivisionError: print("Error: Division by zero")
Common types of exceptions in Python:
ZeroDivisionError
, ValueError
, TypeError
, FileNotFoundError
, etc.try: num = int("not_an_integer") except ValueError: print("Error: Invalid conversion to integer")
Error handling and exceptions in Python programming:
try: # Code that may raise an exception result = 10 / 0 except ZeroDivisionError: print("Error: Division by zero")
Handling specific exceptions in Python:
try: result = 10 / 0 except ZeroDivisionError: print("Error: Division by zero") except ValueError: print("Error: Invalid value")
Built-in exception classes in Python:
ZeroDivisionError
, ValueError
, and more.try: num = int("not_an_integer") except ValueError as ve: print(f"Error: {type(ve).__name__} - {ve}")
Common mistakes and pitfalls in Python exception handling:
except
.try: result = 10 / 0 except Exception as e: print(f"Error: {type(e).__name__} - {e}")
Error hierarchy and exception types in Python:
BaseException
at the top and specific exceptions derived from it.try: result = 10 / 0 except BaseException as be: print(f"BaseException: {type(be).__name__} - {be}")
Common scenarios for using try-except in Python:
try-except
to handle potential errors in scenarios like file operations, network requests, etc.try: with open("file.txt", "r") as file: content = file.read() except FileNotFoundError: print("Error: File not found")
Handling multiple exceptions in Python:
try-except
block.try: value = int("not_an_integer") except (ValueError, TypeError): print("Error: Invalid conversion to integer")
Raising custom exceptions in Python:
def custom_function(value): if value < 0: raise ValueError("Value must be non-negative") # Rest of the code try: custom_function(-5) except ValueError as ve: print(f"Custom Error: {ve}")
How to create and use custom exception classes in Python:
class CustomError(Exception): def __init__(self, message="Custom error occurred"): self.message = message super().__init__(self.message) try: raise CustomError("This is a custom exception") except CustomError as ce: print(f"Caught custom exception: {ce}")