Python exception handling

Python Exception Handling

If you have code that might raise an exception, you can protect your program by enclosing it in a try block. After the try block, include an except statement, followed by code to handle the problem as gracefully as possible.

  • try blocks contain statements that might raise an exception.
  • If an exception occurs, the program jumps to the except block.

  • If no exception occurs within the try block, the except block is skipped.

Syntax

Below is the simple syntax of the try…except…else block:

try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception, then execute this block.

Following are a few important points about the above syntax:

  • A try statement can have multiple except statements. This is useful when the try block contains statements that may raise different types of exceptions.
  • You can also provide a general except clause to handle any exception.

  • After the except clause, you can add an else clause. If the code in the try block does not raise an exception, the code in the else block will execute.

  • The else block is a good place for code that doesn’t need the protection of the try block.

Example

This example opens a file, writes to it, and exits in a completely normal manner because no problems occurred.

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print("Error: can't find file or read data")
else:
print("Written content in the file successfully")
fh.close()

It will produce the following output –

Written content in the file successfully

However, if the mode parameter in the open() function is changed to “w”, the program will encounter an IOError in the except block and print the following error message −

Error: can't find file or read data

Leave a Reply

Your email address will not be published. Required fields are marked *