Let us see some of the Python Errors
- NameError
- SyntaxError
- IndentationError
- TypeError
- IndexError
- ValueError
- FileNotFoundError
- ModuleNotFoundError
- ZeroDivisionError
- AttributeError
NameError
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> def myfun():
... print(x)
...
>>> myfun()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in myfun
NameError: name 'x' is not defined
SyntaxError
>>> while True:
... print "Hello World"
File "<stdin>", line 2
print "Hello World"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello World")?
>>> class employee:
... def __init__(self,name,age):
... self.name = name
... self.age = age
...
>>> myobj = employee(01,girish)
File "<stdin>", line 1
employee(01,girish)
^
SyntaxError: invalid token
IndentationError
>>> if 10 > 20:
... print("10 is greater then 20")
File "<stdin>", line 2
print("10 is greater then 20")
^
IndentationError: expected an indented block
>>> for x in "Girish":
... print(x)
File "<stdin>", line 2
print(x)
^
IndentationError: expected an indented block
TypeError
>>> x = 10
>>> print("Number is : " + 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> x = 10
>>> y = "Girish"
>>> x + y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> x = 10
>>> for y in x:
... print(y)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> myTuple = ("One","Two","Three")
>>> myTuple[1]
'Two'
>>> myTuple[1]="Twenty"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> class employee:
... def __init__(self,name,age):
... self.name = name
... self.age = age
...
>>> myobj = employee()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'
IndexError
>>> myList = ["One","Two","Three"]
>>> myList[0]
'One'
>>> myList[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
ValueError
>>> x = int(input("Please enter a number:"))
Please enter a number:sdfaf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'sdfaf'
FileNotFoundError
>>> import sys
>>> f = open("tere.txt")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'tere.txt'
ModuleNotFoundError
>>> import IOError as e
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'IOError'
ZeroDivisionError
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
AttributeError
>>> try:
... print(z)
... except NameError as e:
... print(e.value)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'z' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
AttributeError: 'NameError' object has no attribute 'value'
Exception Handling
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 and are not unconditionally fatal
- try block – test a block of code for errors
- except block – handle the error
- finally block – execute code, regardless of the result of the try- and except blocks
>>> try:
... print(a)
... except:
... print("An exception occured")
...
An exception occured
>>> try:
... print(x)
... except NameError:
... print("Variable x is not defined")
... except:
... print("Something wrong")
...
Variable x is not defined
>>> try:
... print("Welcome")
... except:
... print("Something wrong")
... else:
... print("Nothing wrong")
...
Welcome
Nothing went wrong
>>> try:
... print(x)
... except:
... print("some problem")
... finally:
... print("I always execute")
...
some problem
I always execute
>>> while True:
... try:
... x = int(input("Please enter a number:"))
... break
... except ValueError:
... print("Not a valid number, try again")
...
Please enter a number:fds
Not a valid number, try again
Please enter a number:sadf
Not a valid number, try again
Please enter a number:safdsf
Not a valid number, try again
Please enter a number:44
>>> try:
... print(z)
... except NameError as err:
... print(err)
...
name 'z' is not defined
>>> z
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'z' is not defined
>>> print(0/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> try:
... print(0/0)
... except Exception as err:
... print(err)
...
division by zero
>>> print(10 + "Hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> try:
... print(10 + "hell0")
... except Exception as err:
... print(err)
...
unsupported operand type(s) for +: 'int' and 'str'
>>> import traceback
>>> try:
... 1/0
... except Exception:
... traceback.print_exc()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
>>> try:
... x
... except Exception:
... traceback.print_exc()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'x' is not defined
The raise statement allows the programmer to force a specified exception to occur.
>>> raise NameError("Hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: Hello
>>> raise ValueError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError
>>> raise TestError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'TestError' is not defined
>>> raise KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>> try:
... raise NameError("Hello")
... except NameError:
... print("An Exception Flew By!")
... raise
...
An Exception Flew By!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: Hello
>>> x = 6
>>> if x > 5:
>>> raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
User Defined Exceptions
Programs may name their own exceptions by creating a new exception class. Exceptions should typically be derived from the Exception class, either directly or indirectly.
>>> class MyError(Exception):
... def __init__(self,value):
... self.value = value
... def __str__(self):
... return repr(self.value)
...
>>> try:
... raise MyError(2*2)
... except MyError as e:
... print("My Exception Occured, Value:",e.value)
...
My Exception Occured, Value: 4
>>> raise MyError("Hooo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.MyError: 'Hooo'
>>> salary = int(input("Enter Salary: "))
Enter Salary: 200000
>>> try:
... if (salary >= 150000):
... raise MyError("Salary is more then 150000. Enter less than or equal to 150000")
... except MyError as e:
... print("You got the error:", e.value)
...
You got the error: Salary is more then 150000. Enter less than or equal to 150000
>>>
>>> def fun():
... try:
... name = input("Enter string in caps only ")
... if name.isupper()== False:
... raise EnterOnlyCaps
... except EnterOnlyCaps:
... print("Please enter caps only")
... else:
... print("You have done Great Job")
...
>>> fun()
Enter string in caps only 3r209u0fuvf
Please enter caps only
>>> fun()
Enter string in caps only asfd
Please enter caps only
>>> fun()
Enter string in caps only GIRISH
You have done Great Job
>>>
References
- https://docs.python.org/2/library/exceptions.html
- https://docs.python.org/2/tutorial/errors.html
- https://docs.python.org/3/tutorial/errors.html
Learn more about python programs in our upcoming blog articles.
Happy Learning!