Exception handling is a process in which we handle the runtime errors or exceptional events that may occur during the execution of a program. Python provides a built-in mechanism called
try
and
except
to handle exceptions.
Here is the syntax of how to use exception handling in Python:
1 2 3 4 5 | try: # some code here # this code may throw an exception except SomeException: # code to handle the exception |
The
try
block contains the code that may throw an exception. The
except
block contains the code to handle the exception. If an exception occurs in the
try
block, the code in the
except
block will be executed.
You can also handle multiple exceptions in a single
except
block by separating the exceptions with a comma:
1 2 3 4 5 6 7 | try: # some code here # this code may throw an exception except SomeException: # code to handle SomeException except AnotherException: # code to handle AnotherException |
You can also use the
else
block to specify code that should be executed if no exception occurs:
1 2 3 4 5 6 7 | try: # some code here # this code may throw an exception except SomeException: # code to handle SomeException else: # code to be executed if no exception occurs |
finally
keyword in Exception Handling in Python
Finally, you can use the
finally
block to specify code that should always be executed, whether an exception occurs or not:
1 2 3 4 5 6 7 | try: # some code here # this code may throw an exception except SomeException: # code to handle SomeException finally: # code to be executed whether an exception occurs or not |
By using exception handling, you can write robust code that can handle unexpected errors and continue running without crashing.