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. The 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 preceding part of the error message shows the context where the exception occurred, 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.,The rest of the line provides detail based on the type of exception and what caused it.,If an exception has arguments, they are printed as the last part (‘detail’) of the message for unhandled exceptions.
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>>
while True:
...
try:
...x = int(input("Please enter a number: "))
...
break
...except ValueError:
...print("Oops! That was no valid number. Try again...")
...
...except(RuntimeError, TypeError, NameError):
...pass
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except BaseException as err:
print(f "Unexpected {err=}, {type(err)=}")
raise
In this tutorial, you will learn about different types of errors and exceptions that are built-in to Python. They are raised whenever the Python interpreter encounters errors.,Whenever these types of runtime errors occur, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error occurred.,We can handle these built-in and user-defined exceptions in Python using try, except and finally statements. To learn more about them, visit Python try, except and finally statements.,Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur. We can view all the built-in exceptions using the built-in local() function as follows:
Let's look at one example:
>>> if a < 3 File "<interactive input>" , line 1 if a < 3 ^ SyntaxError: invalid syntax
Let's look at how Python treats these errors:
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero
>>> open("imaginary.txt")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur. We can view all the built-in exceptions using the built-in local()
function as follows:
print(dir(locals()['__builtins__']))
Last Updated : 22 Oct, 2021,GATE CS 2021 Syllabus
- Output:
code start
an error occurs
GeeksForGeeks
Many times though, a program results in an error after it is run even if it doesn't have any syntax error. Such an error is a runtime error, called an exception. A number of built-in exceptions are defined in the Python library. Let's see some common error types. ,The following table lists important built-in exceptions in Python.,Learn how to handle exceptions in Python in the next chapter., The most common reason of an error in a Python program is when a certain statement is not in accordance with the prescribed usage. Such an error is called a syntax error. The Python interpreter immediately reports it, usually along with the reason.
>>> print "hello"
SyntaxError: Missing parentheses in call to 'print'.Did you mean print("hello") ?
>>> L1=[1,2,3]
>>> L1[3]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
L1[3]
IndexError: list index out of range
>>> import notamodule
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
import notamodule
ModuleNotFoundError: No module named 'notamodule'
>>> D1={'1':"aa", '2':"bb", '3':"cc"}
>>> D1['4']
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
D1['4']
KeyError: '4'
>>> from math import cube
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
from math import cube
ImportError: cannot import name 'cube'
>>> it=iter([1,2,3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
next(it)
StopIteration
/usr/include/linux/errno.h
includes /usr/include/asm/errno.h
that includes /usr/include/asm-generic/errno-base.h
.
me @my_pc: ~$ cat / usr / include / asm - generic / errno - base.h | grep 34
#define ERANGE 34 /* Math result not representable */
1e4**100
is processed with float_pow
function from Object/floatobject.c. Partial source code of that function:
static PyObject *
float_pow(PyObject * v, PyObject * w, PyObject * z) {
// 107 lines omitted
if (errno != 0) {
/* We do not expect any errno value other than ERANGE, but
* the range of libm bugs appears unbounded.
*/
PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
PyExc_ValueError);
return NULL;
}
return PyFloat_FromDouble(ix);
}
By Bernd Klein. Last modified: 29 Jun 2022.
n = int(input("Please enter a number: "))
while True:
try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")
def int_input(prompt):
while True:
try:
age = int(input(prompt))
return age
except ValueError as e:
print("Not a proper integer! Try it again")
def dog2human_age(dog_age):
human_age = -1
if dog_age < 0:
human_age = -1
elif dog_age == 0:
human_age = 0
elif dog_age == 1:
human_age = 14
elif dog_age == 2:
human_age = 22
else:
human_age = 22 + (dog_age - 2) * 5
return human_age
age = int_input("Age of your dog? ")
print("Age of the dog: ", dog2human_age(age))
Not a proper integer!Try it again
Not a proper integer!Try it again
Age of the dog: 37
These were some of the built-in excpetion classes which are most commonly encountered while coding in python. For all the exception types in python check the official documentation of python.,Python returns a very detailed exception message for us to understand the origin point and reason for the exception so that it becomes easier for us to fix our code.,Hence syntax errors are the most basic type of errors that you will encounter while coding in python and these can easily be fixed by seeing the error message and correcting the code as per python syntax.,And then in the last line, python tells us which exception/error occured, which in our example above is ZeroDivisionError.
This is the most common and basic error situation where you break any syntax rule like if you are working with Python 3.x version and you write the following code for printing any statement,
print "I love Python!"
Because, Python 3 onwards the syntax for using the print
statement has changed. Similarly if you forget to add colon(:
) at the end of the if
condition, you will get a SyntaxError:
if 7 > 5
print("Yo Yo!")
Let's take the most basic example of dividing a number by zero:
a = 10
b = 0
print("Result of Division: " + str(a / b))
Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them −,Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python: Standard Exceptions.,When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.,If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback.
The syntax for assert is −
assert Expression[, Arguments]
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert(Temperature >= 0), "Colder than absolute zero!"
return ((Temperature - 273) * 1.8) + 32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
When the above code is executed, it produces the following result −
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
This produces the following result −
Written content in the file successfully