Python try exception
try except statements are used to handle exceptions, which are events that occur during the execution of a program that disrupt the normal flow of instructions. Exceptions are usually caused by errors, such as dividing by zero, accessing an index out of bounds, or trying to open a file that doesn't exist.
The try-except statement has two blocks of code: the try block and the except block. The try block contains the code that might raise an exception, and the except block contains the code that will be executed if an exception is raised.
Here is an example of a simple try-except statement to capture all error in a single exception block:
1try: 2 x = 5 / 0 3except Exception: 4 print("Exception error")
To capture specific exception use the builtin exception
1try: 2 x = 5 / 0 3except ZeroDivisionError: 4 print("Cannot divide by zero.")
In this example, the try block contains a division operation that will raise a ZeroDivisionError exception if the denominator is zero. The except block catches this exception and prints an error message.
Capture multiple exceptions
You can also catch multiple exceptions using multiple except blocks:
1try: 2 x = int("hello") 3except ValueError: 4 print("Invalid input.") 5except TypeError: 6 print("Invalid type.")
In this example, the try block tries to convert a string to an integer, which will raise a ValueError exception if the string is not a valid number, or a TypeError exception if the input is not a string. The first except block catches the ValueError exception and prints an error message, the second except block catches the TypeError exception and prints another error message.
Capture multiple exception in a single except block
1try: 2 x = int("hello") 3except (ZeroDivisionError, ValueError, TypeError): 4 print("Error")
You can also use the finally block to put code that must be executed regardless of whether an exception was raised or not.
1try: 2 x = int("hello") 3except ValueError: 4 print("Invalid input.") 5finally: 6 print("This will always be executed.")
In this example, the finally block contains a print statement that will be executed whether the exception was raised or not.
else block in the try-except statement is used to specify a block of code to be executed if no exception occurs.
1try: 2 x = 1 / 2 3except ZeroDivisionError: 4 print("Cannot divide by zero") 5else: 6 print("No exception raised")
Raise custom exception
use raise keyword to make custom exception
1try: 2 raise("Make exception") 3except Exception: 4 print("Custom exception")
Capture exception message
In exception block add
as followed by any name used to get the error message
1try: 2 x = 1 / 0 3except Exception as e: 4 print("Error:", e) # output: Error: division by zero