In this article you will learn python exception handling (python try and except).
Python has many built-in exceptions when something goes wrong in a program compiler shows that with error name.
New here?
Start learning Python from scratch for Free.
- Introduction to Programming – Day1
- Introduction to Algorithms – Day 2
- Python operators and variables – Day 3
- Python Control Structures – Day 4
- Functions in Python – Day 5 of Python Series
- How to setup Eclipse IDE for Python? – 6th Day of Python Series
- Collection Data types in Python – 7th Day of Python Series
- Python Debugging and Testing –Python Series-8th day

Python exception handling

Python Try Except
Python also allows us to handle different errors that can occur separately. That means you can have a different action or message for every unique error that occurs.
Here is an example
def calculate_expenditure(list_of_expenditure): total=0 try: for expenditure in list_of_expenditure: total+=expenditure print("Total:",total) avg=total/num_values print("Average:",avg) except ZeroDivisionError: print("Divide by Zero error") except TypeError: print("Wrong data type") except: print("Some error occured" list_of_values=[100,200,300,"400",500] num_values=0 calculate_expenditure(list_of_values)
We can write our message in except block if try block failed to execute then the message in except block for that specific error will be shown.
Note:
- Default except block is the one without any type mentioned.
- If an error occurs and the matching except block is found, then that is executed.
- If an error occurs and the matching except block is not found, it executes the default except block.
- If an error occurs and the matching except block is not found and if the default except block is also not found, the code crashes.
- The default except for block, if present should be the last except block, otherwise it will result in a runtime error.
Some built-in exceptions in python:
Built-in Exception | When it will be raised | Example |
ZeroDivisionError | When a value is divided by zero | num_list=[]total=0avg=total/len(num_list) |
TypeError | When we try to do an operation with incompatible data types | total=10total+=”20″ |
NameError | When we try to access a variable which is not defined | avg=total/10 where total is not defined |
IndexError | When we try to access an index value which is out of range | num_list=[1,2,3,4]value=num_list[4] |
ValueError | When we use a valid data type for an argument of a built-in function but passes an invalid value for it | #string is a valid data type for int() but the value “A” is invalid, as “A” can’t be converted into int.value=”A”num=int(value) |
Finally block in python
Python try except
That is indeed fortunate. Sometimes in programming, we need to execute some code irrespective of whether the primary program logic itself succeeds or fails to do its job. In Python, we can achieve this using a finally block. Let’s see it.
A finally block of statement is an optional part of the try-except statements. A code written inside the finally block will ALWAYS be executed.
Example:
balance=1000 amount="300Rs" def take_card(): print("Take the card out of ATM") try: if balance>=int(amount): print("Withdraw") else: print("Invalid amount") except TypeError: print("Type Error Occurred") except ValueError: print("Value Error Occurred") except: print("Some error Occurred") finally: take_card()
The question covered In this Article

- What is Exception handling in python?
- What is Python Try except?
- Try and except in Python.
FAQ
1. What is Exception handling in Python?
An exception is an event that occurs during the program that interrupts the normal flow of execution.
2. What is Try in python?
Try in python
3. Why exception handling is needed?
The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application that is why we use exception handling
Related Reads:
- Introduction to Programming – Day1
- Introduction to Algorithms – Day 2
- Python operators and variables – Day 3
- Python Control Structures – Day 4
- Functions in Python – Day 5 of Python Series
- How to setup Eclipse IDE for Python? – 6th Day of Python Series
- Collection Data types in Python – 7th Day of Python Series
- Python Debugging and Testing –Python Series-8th day
GIPHY App Key not set. Please check settings