Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.

  • The try: block contains statements which are susceptible for exception

  • If exception occurs, the program jumps to the except: block.

  • If no exception in the try: block, the except: block is skipped.

Syntax

Here is the simple syntax of try...except...else blocks −

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.

Here are few important points about the above-mentioned syntax −

  • A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.

  • You can also provide a generic except clause, which handles any exception.

  • After the except clause(s), you can include an else clause. The code in the else block executes if the code in the try: block does not raise an exception.

  • The else block is a good place for code that does not need the try: block's protection.

Example

This example opens a file, writes content in the file and comes out gracefully because there is no problem at all.

 
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, change the mode parameter in open() function to "w". If the testfile is not already present, the program encounters IOError in except block, and prints following error message −

Error: can't find file or read data


The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Cette réponse était-elle pertinente? 1 Utilisateurs l'ont trouvée utile (1 Votes)