Hello guys! Here we are going to see five Python exception handling examples. So, let’s see
- Catching a specific exception:
try: x = int("hello") except ValueError: print("Invalid input")
In this example, the int("hello")
the function call will raise a ValueError
, because the string “hello” cannot be converted to an integer. The try
block catches the ValueError
, and the except
block prints “Invalid input” to the console.
- Catching multiple exceptions:
try: file = open("myfile.txt") x = int("hello") except ValueError: print("Invalid input") except FileNotFoundError: print("File not found")
In this example, the try
block contains two lines of code that might raise exceptions: opening a file that doesn’t exist, and converting a string to an integer. The except
blocks handle each exception type separately.
- Using the
finally
block:
try: x = 5 / 0 except ZeroDivisionError: print("Division by zero") finally: print("This code always runs")
In this example, the try
block attempts to divide 5 by 0, which will raise a ZeroDivisionError
. The except
block prints a message to the console and the finally
block prints “This code always runs”, regardless of whether an exception was raised.
- Raising an exception explicitly:
x = -1 if x < 0: raise ValueError("Negative numbers not allowed")
In this example, if the value of x
is less than 0, a ValueError
is raised with the message “Negative numbers not allowed”.
- Catching any exception:
try: x = int("hello") except: print("Something went wrong")
In the above example, the except
block catches any type of exception that might be raised in the try
block, and prints “Something went wrong”. While catching any exception can be useful for debugging or logging purposes, it’s generally better to catch specific exception types, so you can handle them appropriately.