Python Menu

Exceptions in Python


An exception can be defined as an abnormal condition in a program. It interrupts the flow of the program. Whenever an exception occurs, the program halts the execution, and thus the further code is not executed.

In general an exception is an error that happens during execution of a program. When that error occurs, it terminates program execution. In Python, an error can be a syntax error or an exception. Now we will see what an exception is and how it differs from a syntax error.

Syntax errors occur when the parser detects an incorrect statement.


expdemo.py
a=5
b=0
print(a/b))
Output:
File "expdemo.py", line 3
print(a/b))
SyntaxError: invalid syntax

The arrow indicates where the parser ran into the syntax error. In this example, there was one more bracket. Remove it and run your code again

expdemo.py
a=5
b=0
print(a/b)
Output:
Traceback (most recent call last):
  File "expdemo.py", line 3, in 
    print(a/b)
ZeroDivisionError: division by zero

This time, the parser ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into.

Instead of showing the message exception error, Python details what type of exception error was encountered. In this case, it was a ZeroDivisionError.

Standard Exceptions in Python

Python supports various built-in exceptions, the commonly used exceptions are

•  NameError: It occurs when a name is not found.i.e attempt to access an undeclared variable

Example:
a=5
c=a+b
print("Sum =",c)
Output:
Traceback (most recent call last):
  File "expdemo.py", line 2, in 
    c=a+b
NameError: name 'b' is not defined

•  ZeroDivisionError: Occurs when a number is divided by zero.

Example:
a=5
b=0
print(a/b)
Output:
Traceback (most recent call last):
  File "expdemo.py", line 3, in 
    print(a/b)
ZeroDivisionError: division by zero

•  ValueError: Occurs when an inappropriate value assigned to variable.

Example:
a=int(input("Enter a number : "))
b=int(input("Enter a number : "))
print("Sum =",a+b)
Output:
Enter a number : 23
Enter a number : abc
Traceback (most recent call last):
  File "expdemo.py", line 2, in 
    b=int(input("Enter a number : "))
ValueError: invalid literal for int() with base 10: 'abc'

•  IndexError: Occurs when we request for an out-of-range index for sequence

Example:
ls=['c','java','python']
print("list item is :",ls[5])
Output:
Traceback (most recent call last):
  File "expdemo.py", line 2, in 
    print("list item is :",ls[5])
IndexError: list index out of range.

•  KeyError: Occurs when we request for a non-existent dictionary key

Example:
dic={"name":"Madhu","location":"Hyd"}
print("The age is :",dic["age"])
Output:
Traceback (most recent call last):
  File "expdemo.py", line 2, in 
    print("The age is :",dic["age"])
KeyError: 'age'

•  IOError: Occurs when we request for a non-existent input/output file.

Example:
fn=open("exam.py")
print(fn)
Output:
Traceback (most recent call last):
  File "expdemo.py", line 1, in 
    fn=open("exam.py")
FileNotFoundError: [IOError] No such file or directory: 'exam.py'

Exceptions as Strings

Prior to Python 1.5, standard exceptions were implemented as strings. However, this became limiting in that it did not allow for exceptions to have relationships to each other. As of python 1.5, all standard exceptions are now classes. It is still possible for programmers to generate their own exceptions as strings, but we recommend using exception classes from now on.

Python 2.5 begins the process of deprecating string exceptions from Python forever. In 2.5, raise of string exceptions generates a warning. In 2.6, the catching of string exceptions results in a warning. Since they are rarely used and are being deprecated, we will no longer consider string exceptions.

Creating Exceptions

Python allow programmers to create their own exception class. Exceptions should typically be derived from the Exception class, either directly or indirectly.


Next Topic :Exception handling in Python