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.

  • 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).

  • ValueError − It raises when we pass an inappropriate value to a function.

  • 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.

  • ImportError − If we try to import a module that does not exist.

  • IOError − It occurs when Python can't open a file.

  • 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.

  • 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 and except block can't handle it, then the corresponding exception error will raise.

  • We can have multiple except statements for one try block.

Example

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")

Output

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.

Example

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")

Output

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.

Example

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")

Output

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.

Conclusion

If you have any queries regarding the tutorial, mention them in the comment section.

Updated on: 24-Apr-2020

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements