Unit-V
Python file data printing on screen:
a=str(input("Enter the name of the file with .txt
extension:"))
file2=open(a,'r')
line=[Link]()
while(line!=""):
print(line)
line=[Link]()
[Link]()
Note: We need to create a file and write anything in that.
Reading data from keyboard:
Python provides two built-in functions to read a line of text from
standard input, which by default comes from the keyboard. These
functions are −
raw_input
input
The raw_input Function
The raw_input([prompt]) function reads one line from standard
input and returns it as a string (removing the trailing newline).
#!/usr/bin/python
str = raw_input("Enter your input: ")
print "Received input is : ", str
This prompts you to enter any string and it would display same
string on the screen. When I typed "Hello Python!", its output is
like this −
Enter your input: Hello Python
Received input is : Hello Python
The input Function
The input([prompt]) function is equivalent to raw_input, except
that it assumes the input is a valid Python expression and returns
the evaluated result to you.
#!/usr/bin/python
str = input("Enter your input: ")
print "Received input is : ", str
This would produce the following result against the entered input
−
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]
The file Object Attributes
Once a file is opened and you have one file object, you can get
various information related to that file.
Here is a list of all attributes related to file object −
Sr.N
Modes & Description
o
[Link]
1
Returns true if file is closed, false otherwise.
[Link]
2
Returns access mode with which file was opened.
3 [Link]
Sr.N
Modes & Description
o
Returns name of the file.
[Link]
4 Returns false if space explicitly required with print,
true otherwise.
Example
#!/usr/bin/python
# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]
print "Closed or not : ", [Link]
print "Opening mode : ", [Link]
print "Softspace flag : ", [Link]
Output
This produces the following result −
Name of the file: [Link]
Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method
The close() method of a file object flushes any unwritten
information and closes the file object, after which no more writing
can be done.
Python automatically closes a file when the reference object of a
file is reassigned to another file. It is a good practice to use the
close() method to close a file.
Syntax
[Link]()
Example
#!/usr/bin/python
# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]
# Close opend file
[Link]()
Output
This produces the following result −
Name of the file: [Link]
How to open and close a file in Python
There might arise a situation where one needs to interact with external
files with Python. Python provides inbuilt functions for creating, writing,
and reading files. In this article, we will be discussing how to open an
external file and close the same using Python.
Opening a file in Python
There are two types of files that can be handled in Python, normal text files
and binary files (written in binary language, 0s, and 1s). Opening a file refers
to getting the file ready either for reading or for writing. This can be done
using the open() function. This function returns a file object and takes two
arguments, one that accepts the file name and another that accepts the
mode(Access Mode).
Note: The file should exist in the same directory as the Python script,
otherwise, the full address of the file should be written.
Syntax: File_object = open(“File_Name”, “Access_Mode”)
Parameters:
File_Name: It is the name of the file that needs to be opened.
Access_Mode: Access modes govern the type of operations possible in
the opened file. The below table gives the list of all access mode available
in python
Operation Syntax Description
Read Only R Open text file for reading only.
Read and
r+ Open the file for reading and writing.
Write
Write Only W Open the file for writing.
Write and Open the file for reading and writing. Unlike “r+” is doesn’t
w+
Read raise an I/O error if file doesn’t exist.
Open the file for writing and creates new file if it doesn’t exist.
Append
A All additions are made at the end of the file and no existing
Only
data can be modified.
Open the file for reading and writing and creates new file if it
Append and
a+ doesn’t exist. All additions are made at the end of the file and
Read
no existing data can be modified.
Example 1: Open and read a file using Python
In this example, we will be opening a file to read-only. The initial file looks
like the below:
# open the file using open() function
file = open("[Link]")
# Reading from file
print([Link]())
Here we have opened the file and printed its content.
Output:
Hello Geek!
This is a sample text file for the example.
Example 2: Open and write in a file using Python
In this example, we will be appending new content to the existing file. So the
initial file looks like the below:
# open the file using open() function
file = open("[Link]", 'a')
# Add content in the file
[Link](" This text has been newly appended on the sample
file")
Now if you open the file you will see the below result,
Output:
Example 3: Open and overwrite a file using Python
In this example, we will be overwriting the contents of the sample file with the
below code:
# open the file using open() function
file = open("[Link]", 'w')
# Overwrite the file
[Link](" All content has been overwritten !")
The above code leads to the following result,
Output:
Example 4: Create a file if not exists in Python
The [Link]() method of the pathlib module creates the file at the path
specified in the path of the [Link]().
from pathlib import Path
my_file = Path('test1/[Link]')
my_file.touch(exist_ok=True)
f = open(my__file)
Output:
Closing a file in Python
As you notice, we have not closed any of the files that we operated on in the
above examples. Though Python automatically closes a file if the reference
object of the file is allocated to another file, it is a standard practice to close
an opened file as a closed file reduces the risk of being unwarrantedly
modified or read.
Python has a close() method to close a file. The close() method can be
called more than once and if any operation is performed on a closed file it
raises a ValueError. The below code shows a simple use of close() method
to close an opened file.
Example: Read and close the file using Python:
# open the file using open() function
file = open("[Link]")
# Reading from file
print([Link]())
# closing the file
[Link]()
Now if we try to perform any operation on a closed file like shown below it
raises a ValueError:
# open the file using open() function
file = open("[Link]")
# Reading from file
print([Link]())
# closing the file
[Link]()
# Attempt to write in the file
[Link](" Attempt to write on a closed file !")
Output:
ValueError: I/O operation on closed file.
The write() Method
The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the
string −
Syntax
[Link](string)
Here, passed parameter is the content to be written into the opened file.
Learn Python in-depth with real-world projects through our Python
certification course. Enroll and become a certified expert to boost your
career.
Example
#!/usr/bin/python
# Open a file
fo = open("[Link]", "wb")
[Link]( "Python is a great language.\nYeah its great!!\n")
# Close opend file
[Link]()
The above method would create [Link] file and would write given content in
that file and finally it would close that file. If you would open this file, it would
have following content.
Python is a great language.
Yeah its great!!
The read() Method
The read() method reads a string from an open file. It is important to note that
Python strings can have binary data. apart from text data.
Syntax
[Link]([count])
Here, passed parameter is the number of bytes to be read from the opened file.
This method starts reading from the beginning of the file and if count is missing,
then it tries to read as much as possible, maybe until the end of file.
Example
Let's take a file [Link], which we created above.
#!/usr/bin/python
# Open a file
fo = open("[Link]", "r+")
str = [Link](10);
print "Read String is : ", str
# Close opend file
[Link]()
This produces the following result −
Read String is : Python is
Python Exception Handling
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors
are problems in a program due to which the program will stop the execution.
On the other hand, exceptions are raised when some internal events occur
which change the normal flow of the program.
Different types of exceptions in python:
In Python, there are several built-in Python exceptions that can be raised
when an error occurs during the execution of a program. Here are some of
the most common types of exceptions in Python:
SyntaxError: This exception is raised when the interpreter encounters a
syntax error in the code, such as a misspelled keyword, a missing colon,
or an unbalanced parenthesis.
TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type, such as adding a string to an
integer.
NameError: This exception is raised when a variable or function name is
not found in the current scope.
IndexError: This exception is raised when an index is out of range for a
list, tuple, or other sequence types.
KeyError: This exception is raised when a key is not found in a
dictionary.
ValueError: This exception is raised when a function or method is called
with an invalid argument or input, such as trying to convert a string to an
integer when the string does not represent a valid integer.
AttributeError: This exception is raised when an attribute or method is
not found on an object, such as trying to access a non-existent attribute of
a class instance.
IOError: This exception is raised when an I/O operation, such as reading
or writing a file, fails due to an input/output error.
ZeroDivisionError: This exception is raised when an attempt is made to
divide a number by zero.
ImportError: This exception is raised when an import statement fails to
find or load a module.
These are just a few examples of the many types of exceptions that can
occur in Python. It’s important to handle exceptions properly in your code
using try-except blocks or other error-handling techniques, in order to
gracefully handle errors and prevent the program from crashing.
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong
syntax in the code. It leads to the termination of the program.
Example:
There is a syntax error in the code . The ‘if' statement should be followed
by a colon (:), and the ‘print' statement should be indented to be inside
the ‘if' block.
Python
amount = 10000
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Output:
Exceptions: 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:
Here in this code as we are dividing the ‘marks’ by zero so a error will occur
known as ‘ZeroDivisionError’. ‘ZeroDivisionError’ occurs when we try to
divide any number by 0.
Python
marks = 10000
a = marks / 0
print(a)
Output:
In the above example raised the ZeroDivisionError as we are trying to divide
a number by 0.
Note: Exception is the base class for all the exceptions in Python.
Example:
1) TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type. Here’s an example:
Here a ‘TypeError’ is raised as both the datatypes are different which are
being added.
Python
x = 5
y = "hello"
z = x + y
output:
Traceback (most recent call last):
File "[Link]", line 4, in
<module>
z = x + y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
try catch block to resolve it:
The code attempts to add an integer (‘x') and a string (‘y') together, which is
not a valid operation, and it will raise a ‘TypeError'. The code used
a ‘try' and ‘except' block to catch this exception and print an error
message.
Python
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
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions in
Python. Statements that can raise exceptions are wrapped inside the try
block and the statements that handle the exception are written inside except
block.
Example: Here we are trying to access the array element whose index is out
of bound and handle the corresponding exception.
Python
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Output
Second element = 2
An error occurred
In the above example, the statements that can cause the error are placed
inside the try statement (second print statement in our case). The second
print statement tries to access the fourth element of the list which is not there
and this throws an exception. This exception is then caught by the except
statement.
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.
Python
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
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.
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. The
code within the finally block is always executed.
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:
print('This is always executed')
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.
try:
raise NameError("Hi there")
except NameError:
print ("An exception")
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/[Link]", line 5, in
<module>
raise NameError("Hi there") # Raise Error
NameError: Hi there
Advantages of Exception Handling:
Improved program reliability: By handling exceptions properly, you can
prevent your program from crashing or producing incorrect results due to
unexpected errors or input.
Simplified error handling: Exception handling allows you to separate
error handling code from the main program logic, making it easier to read
and maintain your code.
Cleaner code: With exception handling, you can avoid using complex
conditional statements to check for errors, leading to cleaner and more
readable code.
Easier debugging: When an exception is raised, the Python interpreter
prints a traceback that shows the exact location where the exception
occurred, making it easier to debug your code.
Disadvantages of Exception Handling:
Performance overhead: Exception handling can be slower than using
conditional statements to check for errors, as the interpreter has to
perform additional work to catch and handle the exception.
Increased code complexity: Exception handling can make your code
more complex, especially if you have to handle multiple types of
exceptions or implement complex error handling logic.
Possible security risks: Improperly handled exceptions can potentially
reveal sensitive information or create security vulnerabilities in your code,
so it’s important to handle exceptions carefully and avoid exposing too
much information about your program.
Except clause in python:
except NameError: print("You have a variable that is not defined.") else: print("The 'Try'
code was executed without raising any errors!")
Python Try Except
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors
are the problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal
events occur which changes the normal flow of the program.
Some of the common Exception Errors are :
IOError: if the file can’t be opened
KeyboardInterrupt: when an unrequired key is pressed by the user
ValueError: when the built-in function receives a wrong argument
EOFError: if End-Of-File is hit without reading any data
ImportError: if it is unable to find the module.
Try Except in Python
Try and Except statement is used to handle these errors within our
code in Python. The try block is used to check some code for errors
i.e the code inside the try block will execute when there is no error
in the program. Whereas the code inside the except block will
execute whenever the program encounters some error in the
preceding try block.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
How try() works?
First, the try clause is executed i.e. the code between try.
If there is no exception, then only the try clause will
run, except clause is finished.
If any exception occurs, the try clause will be skipped
and except clause will run.
If any exception occurs, but the except clause within the code
doesn’t handle it, it is passed on to the outer try statements. If
the exception is left unhandled, then the execution stops.
A try statement can have more than one except clause
Code 1: No exception, so the try clause will run.
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
# Look at parameters and note the working of Program
divide(3, 2)
Auxiliary Space: O(1)
Output :
Yeah ! Your answer is : 1
Code 1: There is an exception so only except clause will run.
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
# Look at parameters and note the working of Program
divide(3, 0)
Output :
Sorry ! You are dividing by zero
Code 2: The other way of writing except statement, is shown
below and in this way, it only accepts exceptions that you’re meant
to catch or you can check which error is occurring.
# code
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except Exception as e:
# By this way we can know about the type of error occurring
print("The error is: ",e)
divide(3, "GFG")
divide(3,0)
Output:
The error is: unsupported operand type(s) for //: 'int' and
'str'
The error is: integer division or modulo by zero
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.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
# Program to depict else clause with try-except
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) // (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
# Driver program to test above function
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 exceptions.
Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
# Python program to demonstrate finally
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
Can't divide by zero
This is always executed
Python Raise Keyword
Python Raise Keyword
Python raise Keyword is used to raise exceptions or errors. The raise
keyword raises an error and stops the control flow of the program. It is used
to bring up the current exception in an exception handler so that it can be
handled further up the call stack.
Python Raise Syntax
raise {name_of_ the_ exception_class}
The basic way to raise an error is:
raise Exception(“user text”)
Checking whether an integer is odd or even
In the below code, we check if an integer is even or odd. if the integer is odd
an exception is raised. a is a variable to which we assigned a number 5, as
a is odd, then if loop checks if it’s an odd integer, if it’s an odd integer then
an error is raised.
a = 5
if a % 2 != 0:
raise Exception("The number shouldn't be an odd integer")
Output:
Checking Errror Type
We can check the type of error which have occurred during the execution of
our code. The error can be a ‘ValueError’ or a ‘ZeroDivisionError’ or some
other type of error.
Syntax: raise TypeError
Checking the error type
In the below code, we tried changing the string ‘apple’ assigned to s to
integer and wrote a try-except clause to raise the ValueError. The raise error
keyword raises a value error with the message “String can’t be changed into
an integer”.
s = 'apple'
try:
num = int(s)
except ValueError:
raise ValueError("String can't be changed into integer")
Output
Raising an exception Without Specifying Exception
Class
When we use the raise keyword, there’s no compulsion to give an exception
class along with it. When we do not give any exception class name with the
raise keyword, it reraises the exception that last occurred.
Example
In the above code, we tried changing the string ‘apple’ to integer and wrote a
try-except clause to raise the ValueError. The code is the same as before
except that we don’t provide an exception class, it reraises the exception that
was last occurred.
s = 'apple'
try:
num = int(s)
except:
raise
Output:
Advantages of the raise keyword
It helps us raise error exceptions when we may run into situations where
execution can’t proceed.
It helps us raise error in Python that is caught.
Raise allows us to throw one exception at any time.
It is useful when we want to work with input validations.
User-defined Exceptions in Python with
Examples
User-Defined Exception in Python
Exceptions need to be derived from the Exception class, either directly or
indirectly. Although not mandatory, most of the exceptions are named as
names that end in “Error” similar to the naming of the standard exceptions
in python. For example,
# A python program to create user-defined exception
# class MyError is derived from super class Exception
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
[Link] = value
# __str__ is to print() the value
def __str__(self):
return(repr([Link]))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occurred: ', [Link])
Output
A New Exception occurred: 6
Customizing Exception Classes
To know more about class Exception, run the code below
help(Exception)
Output
Help on class Exception in module exceptions:
class Exception(BaseException)
| Common base class for all non-exit exceptions.
|
| Method resolution order:
| Exception
| BaseException
| __builtin__.object
|
| Methods defined here:
|
| __init__(...)
| x.__init__(...) initializes x; see help(type(x)) for
signature
|
|
---------------------------------------------------------------
-------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a
subtype of T
|
|
---------------------------------------------------------------
-------
| Methods inherited from BaseException:
|
| __delattr__(...)
| x.__delattr__('name') <==> del [Link]
|
| __getattribute__(...)
| x.__getattribute__('name') <==> [Link]
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __getslice__(...)
| x.__getslice__(i, j) <==> x[i:j]
|
| Use of negative indices is not supported.
|
| __reduce__(...)
|
| __repr__(...)
| x.__repr__() <==> repr(x)
|
| __setattr__(...)
| x.__setattr__('name', value) <==> [Link] = value
|
| __setstate__(...)
|
| __str__(...)
| x.__str__() <==> str(x)
|
| __unicode__(...)
|
|
---------------------------------------------------------------
-------
| Data descriptors inherited from BaseException:
|
| __dict__
|
| args
|
| message
Example 1: User-Defined class with Multiple Inheritance
In the below article, we have created a class named “Error” derived from the
class Exception. This base class is inherited by various user-defined classes
to handle different types of python raise an exception with message.
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class zerodivision(Error):
"""Raised when the input value is zero"""
pass
try:
i_num = int(input("Enter a number: "))
if i_num == 0:
raise zerodivision
except zerodivision:
print("Input value is zero, try again!")
print()
Output
Enter a number: 0
Input value is zero, try again!
Example 2: Deriving Error from Super Class Exception
Superclass Exceptions are created when a module needs to handle several
distinct errors. One of the common ways of doing this is to create a base
class for exceptions defined by that module. Further, various subclasses are
defined to create specific exception classes for different error conditions.
# class Error is derived from super class Exception
class Error(Exception):
# Error is derived class for Exception, but
# Base class for exceptions in this module
pass
class TransitionError(Error):
# Raised when an operation attempts a state
# transition that's not allowed.
def __init__(self, prev, nex, msg):
[Link] = prev
[Link] = nex
# Error message thrown is saved in msg
[Link] = msg
try:
raise(TransitionError(2, 3*2, "Not Allowed"))
# Value of Exception is stored in error
except TransitionError as error:
print('Exception occurred: ', [Link])
Output
Exception occurred: Not Allowed
How to use standard Exceptions as a base class?
A runtime error is a class that is a standard exception that is raised when a
generated error does not fall into any category. This program illustrates how
to use runtime error as a base class and network error as a derived class. In
a similar way, an exception can be derived from the standard exceptions of
Python.
Python3
# NetworkError has base RuntimeError
# and not Exception
class Networkerror(RuntimeError):
def __init__(self, arg):
[Link] = arg
try:
raise Networkerror("Error")
except Networkerror as e:
print([Link])
Output
('E', 'r', 'r', 'o', 'r')
---------------------------Unit-V
Complete------------------------------------------------