Python exception handeling
Python exception handeling
in

Python Exception Handling -Try, Except and Finally (day 9th)

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.

Python exception handeling
Python exception handeling

Python exception handling

Python exception handeling
Python exception handeling

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:

  1. Default except block is the one without any type mentioned.
  2. If an error occurs and the matching except block is found, then that is executed.
  3. If an error occurs and the matching except block is not found, it executes the default except block.
  4. 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.
  5. 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 ExceptionWhen it will be raisedExample
ZeroDivisionErrorWhen a value is divided by zeronum_list=[]total=0avg=total/len(num_list)
TypeErrorWhen we try to do an operation with incompatible data typestotal=10total+=”20″
NameErrorWhen we try to access a variable which is not definedavg=total/10 where total is not defined
IndexErrorWhen we try to access an index value which is out of rangenum_list=[1,2,3,4]value=num_list[4]
ValueErrorWhen 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)
Python built in exception

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

Python exception handeling
Python exception handeling
  1. What is Exception handling in python?
  2. What is Python Try except?
  3. 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

Some examples on Try except

Related Reads:

Written by Nishant Tyagi

Author at MyInquisitor

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading…

0

What do you think?

-1 points
Upvote Downvote
Python Debugging

Python Debugging and Testing – Day 8th Python Series

10 useful chrome extensions for designers

10 useful chrome extensions for designers