Try - Except :

Errors may occur while running a program such as invalid input , division by zero, file not found , wrong data type

If an error occurs and is not handled, the program crashes.

The try - except block allows Python to:

  • catch the error
  • handle it gracefully
  • continue program execution

This is known as exception handling.


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.


Syntax :

Python
try: # code that may cause error except: # code to handle error

Example :

Python
try: num = 10 / 0 except: print("Error occurred") #output Error occurred

Handling Specific Exceptions :

Python
try: x = int("abc") except ValueError: print("Invalid number format") 

Handling Multiple Exceptions :

Python
try: a = 10 / 0 except ZeroDivisionError: print("Division not allowed") except ValueError: print("Value error occurred")

Else Block :

Python
try: x = int("10") except ValueError: print("Error") else: print("Conversion successful") 

Finally Block :

Python
try: f = open("data.txt") except FileNotFoundError: print("File not found") finally: print("Task completed") 


ExceptionMeaning
ZeroDivisionErrordividing by zero
ValueErrorwrong value / conversion
TypeErrorwrong data type
IndexErrorinvalid index
KeyErrormissing dictionary key
FileNotFoundErrormissing file
NameErrorundefined variable