Python try-except Statement
Python try-except statement is used for exception handling, allowing you to catch and handle exceptions that occur during the execution of your code.
Syntax
The general syntax of the try-except statement is as follows:
try:
# Python code block where exceptions might occur
# try code goes here
except Exception:
# Python code block to handle the exception
# handling code goes here
else:
# Run this when no exception is raised
finally:
# code that must execute
If you have code that may raise an exception, you can defend your program by placing the code in a try: block. After the try: block, include an except: statement, followed by a block of code that handles the exception.
The try keyword is used to start the code block where you might anticipate exceptions in the code. The except keyword is used to catch specific exceptions within the try block.
The Exception is the type of exception you want to catch and handle. If any exception of this type (or its subclasses) occurs in the try block, the code inside the corresponding except block will be executed.
The else: block is executed when no exception is raised in the try code.
We can use a finally: block along with a try: block. It is a place to put any code that must execute, whether an exception is raised or not.
Example
# Simple Python try-except Statement
# Python tutorials – www.TestingDocs.com
try: # try block
print(20/0)
except ZeroDivisionError: # except block
print(‘An exception occurred. Cannot divide by zero.’)
—
Python Tutorials
Python Tutorial on this website can be found at:
More information on Python is available at the official website: