0% found this document useful (0 votes)
17 views

Handling Errors & Exceptions In: Python

Exceptions in Python refer to errors that occur during execution. Common types include syntax errors, runtime errors, and errors related to incorrect data types or values. The try and except blocks allow code to handle exceptions gracefully. A try block contains code that might raise an exception, while an except block specifies how to handle the exception if it occurs. Unhandled exceptions can cause programs to crash.

Uploaded by

Kshitij Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Handling Errors & Exceptions In: Python

Exceptions in Python refer to errors that occur during execution. Common types include syntax errors, runtime errors, and errors related to incorrect data types or values. The try and except blocks allow code to handle exceptions gracefully. A try block contains code that might raise an exception, while an except block specifies how to handle the exception if it occurs. Unhandled exceptions can cause programs to crash.

Uploaded by

Kshitij Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Handling Errors & Exceptions in Python

Q. What is ‘exception’?
A. Any error which happens during the execution of the code is an exception.
These errors are also called exceptions. Because they usually indicate that
something exceptional (& bad) has happened.

There are several terms and phrases used while working with exceptions. These
are:
 Exception: This term could mean of two things. First, the condition that results in
abnormal program flow or it could be used to refer to an object that represents
the data condition. Each exception has an object that holds information about it.

 Exception handling: The process of handling an exception to normal program


flow.

 ‘Except’ block or ‘catch’ block: Code that handles an abnormal condition is said to
“except” the exception.

 ‘Throw’ or ‘raise’ block: When an abnormal condition to the program flow has
been detected, an instance of an exception object is created. It is then “thrown” or
“raised” to code that will catch it.

 Unhandled exception, uncaught exception: An exception that is thrown, but never


caught. This usually results in error and the program ends or crashes.

 Try block: A set of code that might have an exception thrown in it.

Error exception classes


Exception Class Type Description
Syntax Error Raised when the program code or line
violates the structure or rules about the
structure.
Run-time Error Raised to flag an error when no other
exception type is appropriate.
Name Error Raised if non-existent identifier or variable
used.
Type Error Raised when an incorrect data type is
supplied to an operator or method.
Value Error Raised when the correct data type is
supplied, but it is not an appropriate value.
Zero-Division Error Raised when any division operator used with
0 as division.
Attribute Error Raised when an object does not find an
attribute.
Index Error Raised if index to sequence is out of range or
out of bounds.
Indentation Error Raised upon failure of I/O operation (e.g.,
opening file).
IO Error Raised when a disk fill ups, file is deleted,
moved or the disk is removed.
EOF Error Raised when there is no record or data to
read from a file.
Key Error Raised when a dictionary key is not found in
a dictionary.

 Syntax Error: A syntax error is an error in the source code of a program. It


occurs when we violate any grammatical rules of the programming language.
Example:
o Wrong Code
>>>print “Hello World”
SyntaxError: invalid syntax

o Right Code
>>>print (“Hello World”)
Hello World

 Run-time Error: This error doesn’t appear until after the program has started
running. It is a program error that causes abnormal program termination during
execution. These are like ZeroDivisionError, NameError, TypeError, ValueError,
etc. Example;
o X = (a + b) / c
o The above statement is grammatically correct and will also produce
correct result as soon as c ≠ 0. As soon as c = 0 the code will produce an
error.
o #Python Program
c=0
a = int(input(“Enter value of a: ”))
b = int(input(“Enter value of b: ”))
X = (a + b) / c
Print(“The value of X is: ”, X)
#Python Program Output
Enter the value of a: 20
Enter the value of b: 5
Traceback(most recent call last):
File”C:/Program Files/Python64/Python Program”, line 5, in
<module>
X = (a + b) / c
ZeroDivisionError: division by zero

 NameError: This type of exception occurs, if non-existent identifier or variable


used. In this case of error, you can check if you typed the variable name correctly
or function name correctly, if it should be in quotes, or if you should have defined
it somewhere prior to the line. For example;
o #Python Program
>>>print(Message)
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
print(Message)
NameError: name ‘Message’ is not defined

 Type Error: Raised when an incorrect data type is supplied to an operator or


method. There are several possible causes for Type Error. These are:
o When are you trying to use a improperly. Example: indexing a string, list or
tuple with something other than an integer.
o There is a mismatch between the items in a format string and the items
passed for conversion. This can happen if either the number of items does
not match or an invalid conversion is called for.
o When you are passing the wrong number of arguments to a function or
method. For methods, look at the method definition and check that the first
parameter is self. Then look at the method invocation; make sure you are
invoking the method on an object with the right type and proving the other
arguments correctly.
o For example:
 >>>print(“I am %d feet %d inches tall” % (5, 2, 5))
Traceback (most recent call last):
File “<PythonProgram>”, line 1, <in module>
print(“I am %d feet %d inches tall” % (5, 2, 5))
TypeError: not all arguments converted during string formatting

 >>>print(“I am %d feet %d inches tall” % (5))


Traceback (most recent call last):
File “<PythonProgram>”, line 1, <in module>
print(“I am %d feet %d inches tall” % (5))
TypeError: not enough arguments for format string

 Value Error: Raised when the correct data type is supplied, but it is not an
appropriate value. For example,
o X = int(input(“Please enter a number: ”))
Please enter a number: re
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
X = int(input(“Please enter a number: ”))
ValueError: invalid literal for int() with base 10: ‘re’

 Zero Division Error: When a division expression has zero as the denominator,
this causes Zero Division Error to be raised. For example,
o >>>print(55/0)
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
print(55/0)
ZeroDivisionError: division by zero

 Attribute error: This type of error raises when you are trying to access an
attribute or method that does not exist. If an AttributeError indicates that an object
has NoneType, that means that it is none. For example,
o >>>class Student:
Def_int_(self):
Self.rollno = 100
Self.name = “Ishan”

>>>St = Student()
>>>print(St.Fees)
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
print(St.Fees)
AttributeError: ‘Student’ object has no attribute ‘Fees’

 Index Error: The index you are using to access a list, string, or tuple is greater
than it’s length minus one. When you access the index of a sequence out of it’s
range, then it will raise an exception. For example,
o >>>a = []
>>>print (a[5])
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
print(a[5])
IndexError: list out of range

 Indentation Error: A python program uses indentation to nest blocks. Each


statement in a block must have the same indentation level. An IndentationError
occurs if this rule is broken. But separates blocks may use different indents.
Some common cause of this error include:
o Forgetting to indent the statements within a compound statement.
o Forgetting to indent the statements of a user-defined function.
o For example;
>>>Num = int(input(“Enter a number: ”))
Enter a number: 5
>>>For n in range(0, 1):
print(n)
print(n)
SyntaxError: unexpected indent
 IO Error: The error occurs when a disk could fill up, a user could delete a file
while it is being written, it could be moved, or a USB drive could be pulled out
mid-operation. For example,
o >>>Filename = open(“Test.txt”, “r”)
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
Filename = open (“Test.txt”, “r”)
FileNotFoundError: [Errno 2] No such file or directory: ‘Test.txt’

 EOF Error: This type of error occurs when there is no record or data to read
from a file. For example.
o Eobj = open(“EMD.DAT”, ‘rb’)
try:
while True:
Emp=[]
Emp=load(Eobj)
Print(EMP)
Except EOFError:
Print(‘End of file encounter’)

 Key Error: This type of error occurs when we access a key which does not exist
in a dictionary. For example,
o >>>ListMonths = {‘January’:31, ‘February’:28, ‘March’:31, ‘April’:30,
‘May’:31}
>>>print(ListMonths[“April”])
30
>>> print(ListMonths[“August”])
Traceback (most recent call last):
File “<PythonProgram>”, line 1, in <module>
print(ListMonths[“August”])
KeyError: ‘August’

Handling Exceptions
Exception handling is all about ensuring when your program encounters an issue, it will
continue to run and provide informative feedback to the end-user or program
administrative. So, effective exception handling will make your programs more robust
and easier to debug.
Try…except Blocks

You might also like