ERRORS AND EXCEPTIONS Handling In Python

ERRORS AND EXCEPTIONS

There are two distinguishable kinds of errors: syntax errors and exceptions.

Syntax Errors

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python.

Syntax error is an error in the syntax of a sequence of characters or tokens that is intended to be written in python.

For compiled languages, syntax errors are detected at compile-time. A program will not compile until all syntax errors are corrected. For interpreted languages, however, a syntax error may be detected during program execution, and an interpreter's error messages might not differentiate syntax errors from errors of other kinds.


Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions.

You will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, result in error messages as shown Below:

Example 1:

 55+(5/0)

This will give an error as shown below.

Traceback (most recent call last):
  File "C:\Users\Python\Error.py", line 1, in <module>
    55+(5/0)
ZeroDivisionError: division by zero
</module>

Example 2:

 5+ repeat*2

This will give an error as shown below.

Traceback (most recent call last):
  File "C:\Users\Python\Error.py", line 1, in <module>
    5+ repeat*2
NameError: name 'repeat' is not defined
</module>	

Example 3:

 '5'+5

This will give an error as shown below.

Traceback (most recent call last):
  File "C:\Users\Python\Error.py", line 1, in <module>
    '5'+5
TypeError: can only concatenate str (not "int") to str
</module>	

The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError.

he string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention).

Standard exception names are built-in identifiers (not reserved keywords).


The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception happened, in the form of a stack traceback.

In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.


Python’s built-in exceptions lists and their meanings.


EXCEPTION NAME DESCRIPTION
Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point to any object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it.
EnvironmentError Base class for all exceptions that occur outside the Python environment.
IOError Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
OSError Raised for operating system-related errors.
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.
SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.
SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
TypeError Raised when an operation or function is attempted that is invalid for the specified data type.
ValueError Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
RuntimeError Raised when a generated error does not fall into any category.
NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.


HANDLING EXCEPTIONS

Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them.

    ➤ Exception Handling:

    ➤ Assertions:


Exception Handling

    An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions.

    In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

    When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.

    If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.


Syntax:

Here is simple syntax of try....except...else blocks −

 try:
 	You do your operations here;
 	......................
 except ExceptionI:
 	If there is ExceptionI, then execute this block.
 except ExceptionII:
 	If there is ExceptionII, then execute this block.
 	......................
 else:
 	If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax −

    ➤ A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.

    ➤ You can also provide a generic except clause, which handles any exception.

    ➤ After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.

    ➤ The else-block is a good place for code that does not need the try: block's protection.


Example 1:

This example opens a file with write mode, writes content in the file and comes out gracefully because there is no problem at all

This produces the following result:

Output:

 Written successfully	

Example 2:

This example opens a file with read mode, and tries to write the file where you do not have write permission, so it raises an exception

This produces the following result

 Error: File don't have read permission

The except Clause with No Exceptions

You can also use the except statement with no exceptions defined as follows −

Syntax:

try:
	 You do your operations here;
 	......................
 except:
	 If there is any exception, then execute this block.
 	......................
 else:
	 If there is no exception then execute this block.

This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.

The except Clause with Multiple Exceptions

You can also use the same except statement to handle multiple exceptions as follows −

Syntax:

 try:
	 You do your operations here;
	 ......................
 except(Exception1[, Exception2[,...ExceptionN]]]):
 	If there is any exception from the given exception list, then execute this block.
	......................
 else:
 	If there is no exception then execute this block.

The try-finally Clause

You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this −

Syntax:

 try:
 	You do your operations here;
 	......................
 	Due to any exception, this may be skipped.
 finally:
 	This would always be executed.
 	......................

You cannot use else clause as well along with a finally clause.


Example 1:

This example opens a file with write mode, writes content in the file and comes out gracefully because there is no problem at all


This produces the following result

Output:

 Written successfully
 Closing file

xample 2:

This example opens a file with read mode, and tries to write the file where you do not have write permission, so it raises an exception

This produces the following result

Output:

 Error: File don't have read permission
 Closing file

In the above two examples, one script didn‟t raise exception and another script raise exception. But we can see that in both cases finally block gets executed.


Argument of an Exception

An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows −

Syntax:

 try:
	 You do your operations here;
	 ......................
 except ExceptionType, Argument:
	 You can print value of Argument here...

If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.

This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.


Example :

Following is an example for a single exception

This produces the following result

Output:

 The argument is not a numbers
 invalid literal for int() with base 10: 'abc'

Hierarchical Exceptions Handle

Exception handlers don‟t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause.

For example:

This produces the following result

 Handling run-time error: integer division or modulo by zero

In this example exception is raised in this_fails() function. But, because of this_fails() function don‟t have except block exception is thrown to the caller function. As there is a except block, it will handle the exception.

Raising an Exceptions

You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows.

Syntax:

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

Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.

The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception.

Example :

An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows −

 def functionName( level ):
     if level < 1:
         raise ("Invalid level!", level)
 # if we raise the exception, code below to this not executed

Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string.

For example, to capture above exception, we must write the except clause as follows

 try:
	 Business Logic here...
 except "Invalid level!":
	 Exception handling here...
 else:
	 Rest of the code here...