Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - Exception Handling

Python

python logo

In this tutorial we will learn about exception handlings in Python.

What is an exception?

An exception is an event that disrupts the normal execution of a given program.

In Python an exception is an object that represents an error.

When our Python program raises an exception it must be handled immediately otherwise it terminates the execution of the program.

Handling exception

We use the try and except block to handle exceptions in Python.

The try block

If we have a piece of code that we think might raise an error we put that piece of code inside a try block.

Syntax:

try:
  #
  # some code goes here...
  #

The except block

We use the except block to handle the exception raised by the piece of code inside the try block.

Syntax:

try:
  #
  # some code goes here...
  #
except:
  #
  # some error handling code goes here...
  #

A try block can raise more than one type of exception and hence we can have multiple except attached to a given try block.

Syntax:

try:
  #
  # some code goes here...
  #
except Exception1:
  #
  # some error handling code goes here...
  #
except Exception2:
  #
  # some error handling code goes here...
  #

The else block

The else block holds a piece of code that is executed if no error is raised.

Syntax:

try:
  #
  # some code goes here...
  #
except:
  #
  # some error handling code goes here...
  #
else:
  #
  # some code goes here...
  #

The finally block

We use the finally block to put a piece of code that we want to execute regardless of the try-except block.

The finally block is a good place to release resources like closing files or closing database connections.

Syntax:

try:
  #
  # some code goes here...
  #
except:
  #
  # some error handling code goes here...
  #
finally:
  #
  # some code goes here...
  #

Example #1

In the following Python program we are trying to create a new file using the open function. If the file exists then it will raise an error which we will handle using the try-except block.

try:
    # create new file
    fobj = open("sample.txt", "x")
    print("File created!")
except:
    print("Failed to create file.")

The first time we run the above code we will get "File created!" as the output.

If we run the code again for the second time it will raise an error as the file already exists and we will get "Failed to create file." as the output.

Example #2

In the following Python program we are using try-except-else block.

try:
    # create new file
    fobj = open("sample.txt", "w")
    print("File opened in write mode.")
except:
    print("Failed to create file.")
else:
    fobj.close()
    print("File closed.")

If we execute the above code we will get the following output.

File opened in write mode.
File closed.

Example #3

In the following Python program we are using try-except-finally block.

try:
    # create new file
    fobj = open("sample.txt", "w")
    print("File opened in write mode.")
except:
    print("Failed to create file.")
finally:
    fobj.close()
    print("File closed.")

If we execute the above code we will get the following output.

File opened in write mode.
File closed.

Example #4

In the following Python program we are taking user input and dividing them.

try:

    # take user input
    x = input("Enter 1st number x:")
    y = input("Enter 2nd number y:")

    # convert to number and divide
    result = float(x) / float(y)

    # output
    print("x/y =", result)

except ZeroDivisionError:

    # this handles specific error

    # if y is 0 then this message is prompted
    print("Can't divide by zero.")

except:

    # this handles generalised error
    print("An error occurred.")
    

And here are some of the outputs for the above code.

Output #1

Enter 1st number x:10
Enter 2nd number y:20
x/y = 0.5

Output #2

Enter 1st number x:10
Enter 2nd number y:unknown
An error occurred.

Output #3

Enter 1st number x:10
Enter 2nd number y:0
Can't divide by zero.