Python Exception Handling

Python Exception Handling Using try, except and finally statement

Python Exception Handling: An exception is an error which happens at the time of execution of a program. However, while running a program, Python generates an exception that should be handled to avoid your program to crash. In Python language, exceptions trigger automatically on errors, or they can be triggered and intercepted by your code.

The exception indicates that, although the event can occur, this type of event happens infrequently. When the method is not able to handle the exception, it is thrown to its caller function. Eventually, when an exception is thrown out of the main function, the program is terminated abruptly.

Python provides a way to handle the exception so that the code can be executed without any interruption. If we do not handle the exception, the interpreter doesn’t execute all the code that exists after the exception.

Python has many built-in exceptions that enable our program to run without interruption and give the output.

Python has many built-in exceptions that are raised when your program encounters an error (something in the program goes wrong).

When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.

Common Exceptions in Python

Python provides the number of built-in exceptions, but here we are describing the common standard exceptions. A list of common exceptions that can be thrown from a standard Python program is given below.

  1. ZeroDivisionError: Occurs when a number is divided by zero.
  2. NameError: It occurs when a name is not found. It may be local or global.
  3. IndentationError: If incorrect indentation is given.
  4. IOError: It occurs when Input Output operation fails.
  5. EOFError: It occurs when the end of the file is reached, and yet operations are being performed.

Use of Exception:

Here are the reasons for using exceptions in Python:

  • Exception handling allows you to separate error-handling code from normal code.
  • An exception is a Python object which represents an error.
  • As with code comments, exceptions help you to remind yourself of what the program expects.
  • It clarifies the code and enhances readability.
  • Allows you to stimulate consequences as the error-handling takes place at one place and in one manner.
  • An exception is a convenient method for handling error messages.
  • In Python, you can raise an exception in the program by using the raise exception method.
  • Raising an exception helps you to break the current code execution and returns the exception back to exception until it is handled.
  • Processing exceptions for components which can’t handle them directly.

Types of Exceptions:

In Python there are 2 types of exceptions are possible.

1) Predefined Exceptions

2) User Defined Exceptions

 

1) Predefined Exceptions:

Also known as inbuilt exceptions.

The exceptions which are raised automatically by Python virtual machine whenver a particular event occurs are called pre-defined exceptions.

Eg 1: Whenever we are trying to perform Division by zero, automatically Python will raise ZeroDivisionError.

print(10/0)

 

2) User Defined Exceptions:

Also known as Customized Exceptions or Programatic Exceptions

Some time we have to define and raise exceptions explicitly to indicate that something goes wrong, such type of exceptions are called User Defined Exceptions or Customized Exceptions

Programmer is responsible to define these exceptions and Python not having any idea about these. Hence we have to raise explicitly based on our requirement by using “raise” keyword.

Eg:

Ø InSufficientFundsException

Ø InvalidInputException

Ø TooYoungException

Ø TooOldException

 

Python Exception Handling Mechanism

Exception handling is managed by the following 5 keywords:

  1. try
  2. catch
  3. finally
  4. throw

1) Try Statement in python:

A try statement includes keyword try, followed by a colon (:) and a suite of code in which exceptions may occur. It has one or more clauses.

During the execution of the try statement, if no exceptions occurred then, the interpreter ignores the exception handlers for that specific try statement.

In case, if any exception occurs in a try suite, the try suite expires and program control transfers to the matching except handler following the try suite.

Syntax:

try:

statement(s)

2) Catch Statement in python:

Catch blocks take one argument at a time, which is the type of exception that it is likely to catch. These arguments may range from a specific type of exception which can be varied to a catch-all category of exceptions.

try

}

catch (ArrayIndexOutOfBoundsException e) {

System.err.printin(“Caught first ” + e.getMessage()); } catch (IOException e) {

System.err.printin(“Caught second ” + e.getMessage());

}

3) Finally Statement in Python

Finally block always executes irrespective of an exception being thrown or not. The final keyword allows you to create a block of code that follows a try-catch block.

Finally, clause is optional. It is intended to define clean-up actions which should be that executed in all conditions.

try:

raise KeyboardInterrupt

finally:

print ‘welcome, world!’

Output

Welcome, world!

KeyboardInterrupt

Finally, clause is executed before try statement.

4) Raise Statement in Python

The raise statement specifies an argument which initializes the exception object. Here, a comma follows the exception name, and argument or tuple of the argument that follows the comma.

Syntax:

raise [Exception [, args [, traceback]]]

An exception is an error which happened during the execution of a program.

The exception indicates that, although the event can occur, this type of event happens infrequently.

Common Examples of Exception are 1) Division by Zero, 2) Accessing a file which is not existent, 3) Addition of two incompatible types.

An exception is a Python object which represents an error.

A try statement includes keyword try, followed by a colon (:) and a suite of code in which exceptions may occur. It has one or more clauses.

Catch blocks take one argument at a time, which is the type of exception that it is likely to catch.

The raise statement specifies an argument which initializes the exception object.

Finally, block always executes irrespective of an exception being thrown or not.

What is multithreading in Python?

This blog covers the basics of multithreading in Python programming language. Just like multiprocessing, multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used.

Let us first understand the concept of thread..

What is Thread?

In computing, a process is an instance of a computer program that is being executed. Any process has 3 basic components:

  • An executable program.
  • The associated data needed by the program (variables, work space, buffers, etc.)
  • The execution context of the program (State of process)
  • A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System).

A thread is the smallest unit of a program or process executed independently or scheduled by the Operating System. In the computer system, an Operating System achieves multitasking by dividing the process into threads. A thread is a lightweight process that ensures the execution of the process separately on the system. In Python 3, when multiple processors are running on a program, each processor runs simultaneously to execute its tasks separately.

In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other code. For simplicity, you can assume that a thread is simply a subset of a process.

A thread contains all this information in a Thread Control Block (TCB):

Thread Identifier: Unique id (TID) is assigned to every new thread

Stack pointer: Points to thread’s stack in the process. Stack contains the local variables under thread’s scope.

Program counter: a register which stores the address of the instruction currently being executed by thread.

Thread state: can be running, ready, waiting, start or done.

Thread’s register set: registers assigned to thread for computations.

Parent process Pointer: A pointer to the Process control block (PCB) of the process that the thread lives on.

This is all about Python Exception Handling Using try, except and finally statement.

Related Posts:

Python Tutorial – Learn Python

What is Python? What makes Python so Powerful?

Variables in Python – Constant, Global & Static Variables

Namespacing and Scopes in Python

Operators in Python

Data Types in Python

STRING Data Type in Python

LIST Data Structure in PYTHON

TUPLE Data Structure in PYTHON

Differences between List and Tuple

SET Data Structure in PYTHON

DICTIONARY Data Structure in PYTHON

Database Programming in Python

What is Multithreading in Python?

File Handling in Python

Python Random module

Python reduce() Function

Python map() Function

Python filter() Function

Lambda Function in PYTHON (Anonymous Function)

Python Interview Question And Answers