Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

try catch
python

What is a try-except block in python?

Educative Answers Team

A try and except block is used for error handling in Python.

  • Try: Helps to test the code. If the code inside the try block is error free it is executed. Otherwise the error gets caught and control goes to the except block.
  • Except: Except displays the error message.
  • Else: Executes if there is no error in the code in the try block.
  • Finally: Executes independently of the try-except block results.

The Else and Finally block are optional but it is considered a good programming practice to include them.

Type of error messages

There are two types of error that can occur:

  • Syntax Error/Parsing Error: When the Python parser is unable to understand a line of code.
  • Exception: When the error is detected during execution, e.g.,ZeroDivisionError.

List of exception errors

The following are the list of exception error that arises:

  • IOError: When a file can’t be opened
  • KeyboardInterrupt: When an unrequired key is pressed by the user
  • ValueError :When a built-in function receives a wrong argument
  • EOFError :When one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data
  • ImportError: When a module is not found

Syntax

The general syntax is:

try:
    statement1 #test code
except:
    statement2 #error message
finally:
    statement3 #must execute 


svg viewer
Try Catch Finally Block

Examples

1. Try and except block only

The following code explains how error gets caught in the try block and gets printed in the except block:

try:
  print(variable)
except:
  print("Variable is not defined")
  

2. Try with multiple except blocks

If multiple errors may arise after the execution of one try block, we may use multiple except blocks to handle them.

Note: It is compulsory that the keyword NameError is written in front of the first except statement.

try:
  print(variable)
except NameError:
  print("Variable is not defined")
except:
  print("Seeems like something else went wrong")
  

3. Try, except, and else block

The following code explains how else block gets executed when the try executed correctly:

try:
  variable="Python Programming";
  print(variable)
except:
  print("An exception occurred")
else:
  print("Else executes: Try block executed correctly")

4. Try, except, and finally block

The following code explains how error gets caught in the try block and gets printed in the except block and then the finally block gets executed:

try:
  print(variable)
except:
  print("An exception occurred")
finally:
  print("Always execute this block")

RELATED TAGS

try catch
python
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring