try and except in Python Program

In this tutorial, we are going to learn about the try and except of Python. Python has a concept called error and exception handling.
The keywords try and except are used in the error and exception handling.
Basically, we will find two types of errors in Python. They are −
Syntax errors - Python gives these types of error when it doesn't understand a line of code in the program.
Syntax errors - Python gives these types of error when it doesn't understand a line of code in the program.
Exception errors - Errors which are detected during the runtime of the program. Ex:- ZeroDivisionError, ValueError, etc..,
Exception errors - Errors which are detected during the runtime of the program. Ex:- ZeroDivisionError, ValueError, etc..,
We can't stop syntax errors. But, we can intimate if the program runs into an exception error using try-except. Let's see the most common exception errors in Python.
ZeroDivisionError − It occurs when we try to divide any number with zero (0).
ZeroDivisionError − It occurs when we try to divide any number with zero (0).
ValueError − It raises when we pass an inappropriate value to a function.
ValueError − It raises when we pass an inappropriate value to a function.
IndexError − When we try to access an index that is not available.
IndexError − When we try to access an index that is not available.
KeyError − When we try to access a key that's not present in the dictionary.
KeyError − When we try to access a key that's not present in the dictionary.
ImportError − If we try to import a module that does not exist.
ImportError − If we try to import a module that does not exist.
IOError − It occurs when Python can't open a file.
IOError − It occurs when Python can't open a file.
KeyboardInterrupt − It occurs when the user presses an unrequired key.
KeyboardInterrupt − It occurs when the user presses an unrequired key.
There are many exceptional errors in Python. We can handle these easily with the try-except. Let's see the syntax of the try-except first.
# try-except syntax
try:
   # statement
   # statement
   # ...
except:
   # statement
   # statement
   # ...
How Python executes try-except blocks code? Let's see step by step.
First, Python executes the code inside the try block.
First, Python executes the code inside the try block.
If there is no any exception error in the code, then except block won't execute.
If there is no any exception error in the code, then except block won't execute.
If any exception error occurs in the code, then try block will be skipped and except block code will execute**.
If any exception error occurs in the code, then try block will be skipped and except block code will execute**.
If any exception error occurs and except block can't handle it, then the corresponding exception error will raise.
If any exception error occurs and except block can't handle it, then the corresponding exception error will raise.
We can have multiple except statements for one try block.
We can have multiple except statements for one try block.
Let's see an example where there is not any exception error.
 Live Demo
# No exception error
try:
   arr = [1, 2, 3, 4, 5]
   # accesing an item from array with a valid index
   two = arr[1]
   print(f"We didn't get any errors {two}")
except IndexError:
   print("The given index is not valid")
If you run the above program, then you will get the following result.
We didn't get any errors 2
We didn't get any exception errors. So, the code in try block is executed.
Let's see the same example with an invalid index.
 Live Demo
# No exception error
try:
   arr = [1, 2, 3, 4, 5]
   # accesing an item from array with a invalid index
   six = arr[6]
   print(f"We didn't get any errors {six}")
except IndexError:
   print("The given index is not valid")
If you execute the above code, then you will get the following result.
The given index is not valid
We got IndexError in the try block. So, the code in except block is executed.
Let's see what happens if except can't handle the exception error.
 Live Demo
# No exception error
try:
   arr = [1, 2, 3, 4, 5]
   # accesing an item from array with a invalid index
   six = arr[6]
   print(f"We didn't get any errors {six}")
except ValueError:
   print("The given index is not valid")
If run the above code, then you will get the following result.
---------------------------------------------------------------------------
IndexError                               Traceback (most recent call last)
<ipython-input-11-fe3737d0615b> in <module>
      3    arr = [1, 2, 3, 4, 5]
      4    # accesing an item from array with a invalid index
----> 5    six = arr[6]
      6 print(f"We didn't get any errors {six}")
      7 except ValueError:
IndexError: list index out of range
We got an error. We have given ValueError in the except block. But, we got IndexError that didn't handle by the except block. So, we got an error. Be careful while specifying the exception error in the except block.
If you have any queries regarding the tutorial, mention them in the comment section.