Python Exception Handling: Try, Catch, Finally

What is an Exception in Python?

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.

In this Python exceptional handling tutorial, you will learn :

Common Examples of Exception:

Why should you use Exceptions?

Here are the reasons for using exceptions in Python:

Rules of Exceptions

Here are some essential rules of Python exception handling:

Exceptional Handling Mechanism

Exception handling is managed by the following 5 keywords:

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

The Try Statement

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)

The catch Statement

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.

Rules for catch block:

Example:

try
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.printin("Caught first " + e.getMessage()); } catch (IOException e) {
System.err.printin("Caught second " + e.getMessage());
}

Finally Block

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.

The Raise Statement

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]]]

In this syntax, the argument is optional, and at the time of execution, the exception argument value is always none.

Example:

A Python exception can be any value like a string, class, number, or an object. Most of these exceptions which are raised by Python core are classes with an argument which is an instance of the class.

Important Python Errors

Error Type Description
ArithmeticError ArithmeticError act as a base class for all arithmetic exceptions. It is raised for errors in arithmetic operations.
ImportError ImportError is raised when you are trying to import a module which does not present. This kind of exception occurs if you have made typing mistake in the module name or the module which is not present in the standard path.
IndexError An IndexErroris raised when you try to refer a sequence which is out of range.
KeyError When a specific key is not found in a dictionary, a KeyError exception is raised.
NameError A NameError is raised when a name is referred to in code which never exists in the local or global namespace.
ValueError Value error is raised when a function or built-in operation receives an argument which may be of correct type but does not have suitable value.
EOFerror This kind of error raises when one of the built-in functions (input() or raw_input()) reaches an EOF condition without reading any data.
ZeroDivisonError This type of error raised when division or module by zero takes place for all numeric types.
IOError- This kind of error raised when an input/output operation fails.
syntaxError SyntaxErrors raised when there is an error in Python syntax.
IndentationError This error raised when indentation is not properly defined

Other Important Python Exceptions

Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArraylndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment helps you to the array element of an incompatible type.
ClassCastException Invalid cast
MlegalMonitorStateException Illegal monitor operation, like waiting on an unlocked thread.
MlegalStateException Environment or application is in wrong state.
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object which does not implement the Cloneable interface.
Illegal AccessException Access to a class is denied.
InstantiationException Occurs when you attempt to create an object of an interface or abstract class.
CloneNotSupportedException Attempt to clone an object which does not implement the interface.

Error vs. Exceptions

Error Exceptions
All errors in Python are the unchecked type. Exceptions include both checked and unchecked type.
Errors occur at run time which unknown to the compiler. Exceptions can be recover by handling them with the help of try-catch blocks.
Errors are mostly caused by the environment in which an application is running. The application itself causes exceptions.
Examples:
OutofMemoryError
Examples:
Checked Exceptions, SQL exception, NullPointerException,etc.

Summary

 

YOU MIGHT LIKE: