UNIT 4-NEW
UNIT 4-NEW
UNIT 4-NEW
An error is an issue in a program that prevents the program from completing its task. In
comparison, an exception is a condition that interrupts the normal flow of the program.
Both errors and exceptions are a type of runtime error, which means they occur during
the execution of a program.
In simple words, the error is a critical issue that a normal application should not catch,
while an exception is a condition that a program should catch.
Let’s learn more about errors and exceptions by looking at various examples.
Errors in Python
Here is an example of a syntax error where a return outside the function means nothing.
We should not handle errors in a program. Instead, we must create a function that
returns the string.
EXAMPLE
return "DataCamp"
OUTPUT
Input In [1]
return "DataCamp"
^
EXAMPLE
def fun():
return "DataCamp"
OUTPUT
Input In [2]
return "DataCamp"
Exceptions in Python
Exceptions are raised when the program is syntactically correct, but the code
results in an error. This error does not stop the execution of the program,
however, it changes the normal flow of the program.
EXAMPLE
test = 1/0
OUTPUT
---------------------------------------------------------------------------
Runtime Errors:
A runtime error in a program is an error that occurs while the program is
running after being successfully compiled.
Runtime errors are commonly called referred to as “bugs” and are often
found during the debugging process before the software is released.
There are a variety of runtime errors that occur such as logical
errors, Input/Output errors, undefined object errors, division by zero
errors, and many more.
EXAMPLE :
# the ZeroDivisionError
# Driver Code
def main():
a=5
try:
# Division by Zero
print(a / 0)
except ZeroDivisionError as e:
print(f"Error: {e}")
main()
OUTPUT :
Output:
Example 2:
x=5
y = "hello"
try:
z=x+y
except TypeError:
print("Error: cannot add an int and a str")
Output
Error: cannot add an int and a str
a = [1, 2, 3]
try:
except:
Output
Second element = 2
An error occurred
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for
different exceptions. Please note that at most one handler will be executed. For
example, we can add IndexError in the above code. The general syntax for
adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exceptions in the Python
The code defines a function ‘fun(a)' that calculates b based on the input a.
If a is less than 4, it attempts a division by zero, causing
a ‘ZeroDivisionError'. The code calls fun(3) and fun(5) inside a try-except
block. It handles the ZeroDivisionError for fun(3) and
prints “ZeroDivisionError Occurred and Handled.” The ‘NameError' block is
not executed since there are no ‘NameError' exceptions in the code.
Python3
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
except NameError:
Output
ZeroDivisionError Occurred and Handled
If you comment on the line fun(3), the output will be
NameError Occurred and Handled
The output above is so because as soon as python tries to access the value of
b, NameError occurs.
Try with Else Clause
In Python, you can also use the else clause on the try-except block which must
be present after all the except clauses. The code enters the else block only if
the try clause does not raise an exception.
Try with else clause
The code defines a function AbyB(a, b) that calculates c as ((a+b) / (a-b)) and
handles a potential ZeroDivisionError. It prints the result if there’s no division
by zero error. Calling AbyB(2.0, 3.0) calculates and prints -5.0, while
calling AbyB(3.0, 3.0) attempts to divide by zero, resulting in
a ZeroDivisionError, which is caught and “a/b results in 0” is printed.
Python3
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output:
-5.0
a/b result in 0
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and
except blocks. The final block always executes after the normal termination of
the try block or after the try block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
The code attempts to perform integer division by zero, resulting in
a ZeroDivisionError. It catches the exception and prints “Can’t divide by
zero.” Regardless of the exception, the finally block is executed and
prints “This is always executed.”
try:
k = 5//0
print(k)
except ZeroDivisionError:
print("Can't divide by zero")
finally:
Output:
Can't divide by zero
This is always executed
Raising Exception
The raise statement allows the programmer to force a specific exception to
occur. The sole argument in raise indicates the exception to be raised. This
must be either an exception instance or an exception class (a class that derives
from Exception).
This code intentionally raises a NameError with the message “Hi there” using
the raise statement within a try block. Then, it catches
the NameError exception, prints “An exception,” and re-raises the same
exception using raise. This demonstrates how exceptions can be raised and
handled in Python, allowing for custom error messages and further exception
propagation.
Example :
try:
except NameError:
raise
The output of the above code will simply line printed as “An exception” but a
Runtime error will also occur in the last due to the raise statement in the last
line. So, the output on your command line will look like
Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in
<module>
raise NameError("Hi there") # Raise Error
NameError: Hi there
Exception Hierarchy
In Python, exceptions are a way to handle errors and other
exceptional events that may occur during program execution.
Python’s exception hierarchy provides a well-organized way
to categorize and handle different types of exceptions. The
defined exception structure also provides a deterministic way
of handling different types of exceptions with except blocks.
BaseException
├── BaseExceptionGroup
├── GeneratorExit
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ExceptionGroup [BaseExceptionGroup]
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── BlockingIOError
│ ├── ChildProcessError
│ ├── ConnectionError
│ │ ├── BrokenPipeError
│ │ ├── ConnectionAbortedError
│ │ ├── ConnectionRefusedError
│ │ └── ConnectionResetError
│ ├── FileExistsError
│ ├── FileNotFoundError
│ ├── InterruptedError
│ ├── IsADirectoryError
│ ├── NotADirectoryError
│ ├── PermissionError
│ ├── ProcessLookupError
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
│ ├── NotImplementedError
│ └── RecursionError
├── StopAsyncIteration
├── StopIteration
├── SyntaxError
│ └── IndentationError
│ └── TabError
├── SystemError
├── TypeError
├── ValueError
│ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
│ └── UnicodeTranslateError
└── Warning
├── BytesWarning
├── DeprecationWarning
├── EncodingWarning
├── FutureWarning
├── ImportWarning
├── PendingDeprecationWarning
├── ResourceWarning
├── RuntimeWarning
├── SyntaxWarning
├── UnicodeWarning
└── UserWarning
try:
# some code that may raise an exception
except (ExceptionType1, ExceptionType2):
# handle the exception
In this example, both ExceptionType1 and ExceptionType2 are
exceptions that you want to catch. If the code in the try block
raises an instance of either of these exceptions, the code in
the except block will execute.
try:
# some code that may raise an exception
except (TypeError, ValueError):
# handle the exception
Example
try:
result = 10 / n
try:
# some code that may raise an exception
except TypeError:
# handle the TypeError
except ValueError:
# handle the ValueError
the code in the first except block will execute. If the code
raises a ValueError, the code in the second except block will
execute.
Example:
try:
f = open('missing')
except OSError:
print('It failed')
except FileNotFoundError:
file1 = open("MyFile1.txt","a")
f = open("myfile.txt", "x")
We've now created a new empty text file! But if you retry the
code above – for example, if you try to create a new file with the
same name as you used above (if you want to reuse the
filename above) you will get an error notifying you that the file
already exists. It'll look like the image below:
"w" – Write: this command will create a new text file
whether or not there is a file in the memory with the
new specified name. It does not return an error if it
finds an existing file with the same name – instead it
will overwrite the existing file.
Example of how to create a file with the "w" command:
f = open("myfile.txt", "w")
#This "w" command can also be used create a new file but unlike the the "x" command
the "w" command will overwrite any existing file found with the same file name.
With the code above, whether the file exists or the file doesn't
exist in the memory, you can still go ahead and use that code.
Just keep in mind that it will overwrite the file if it finds an
existing file with the same name.
How to Write to a File in Python
There are two methods of writing to a file in Python, which are:
The write() method:
This function inserts the string into the text file on a single line.
Based on the file we have created above, the below line of code
will insert the string into the created text file, which is
"myfile.txt.”
file.write("Hello There\n")
The writelines() method:
This function inserts multiple strings at the same time. A list of
string elements is created, and each string is then added to the
text file.
Using the previously created file above, the below line of code
will insert the string into the created text file, which is
"myfile.txt.”
file = open("myfile.txt","w")
L = ["This is Lagos \n","This is Python \n","This is Fcc \n"]
# i assigned ["This is Lagos \n","This is Python \n","This is Fcc \n"] to #variable L, you
can use any letter or word of your choice.
# Variable are containers in which values can be stored.
# The \n is placed to indicate the end of the line.
file1.write("Hello \n")
file1.writelines(L)
print(file1.read())
print()
file1.seek(0)
print()
file1.seek(0)
print(file1.read(9))
print()
file1.seek(0)
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is
London \n']