Python Exception Handling: try, catch, finally & raise [Example]

What is an Exception Handling 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.

Common Examples of Exception

  • Division by Zero
  • Accessing a file which does not exist.
  • Addition of two incompatible types
  • Trying to access a nonexistent index of a sequence
  • Removing the table from the disconnected database server.
  • ATM withdrawal of more than the available amount

Why should you use Exceptions?

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 helps 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 expection until it is handled.
  • Processing exceptions for components which can’t handle them directly.

Rules of Exceptions

Here are some essential rules of Python exception handling:

  • Exceptions must be class objects
  • For class exceptions, you can use try statement with an except clause which mentions a particular class.
  • Even if a statement or expression is syntactically correct, it may display an error when an attempt is made to execute it.
  • Errors found during execution are called exceptions, and they are not unconditionally fatal.

Python Exception Handling Mechanism

Exception handling is managed by the following 5 keywords:

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

Python 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:

  • You can define a catch block by using the keyword catch
  • Catch Exception parameter is always enclosed in parentheses
  • It always represents the type of exception that catch block handles.
  • An exception handling code is written between two {} curly braces.
  • You can place multiple catch block within a single try block.
  • You can use a catch block only after the try block.
  • All the catch block should be ordered from subclass to superclass exception.

Example:

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

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.

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

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

  • 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.