Course On Python Basics UNIT – 7: EXCEPTION AND FILE HANDLING IN PYTHON Structure 1.0Learning Objectives 1.1Introduction Exceptions in Python 1.2Catching Exceptions in Python 1.3Raising an Exception in Python 1.4Built-in Exceptions in Python 1.5File handling in Python 1.6File operations in Python 1.7Summary 1.8Glossary 1.9References Page 1 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics 1.0 Learning Objectives After studying this unit, you will be able to: Understand Errors and Exception in Python Explain the process of catching Exceptions Explain the process of raising Exceptions Define built-in Exceptions in Python Explain File handling in Python Understand File handling operations in Python 1.1 Introduction to Exceptions in Python Syntax errors and exceptions are the two forms of mistakes in Python. Errors are issues in a program that causes the program to halt its execution. Exceptions, on the other hand, are raised when internal events occur that disrupt the program's usual flow. Syntax Error: As the name implies, this error is caused by incorrect code syntax. The program is terminated as a result of this. Exception: When your program detects an error, Python raises a number of built-in exceptions (something in the program goes wrong). When one of these exceptions occurs, the Python interpreter suspends the current process and sends the control to the caller process until the problem is resolved. The software will crash if it is not handled properly. Consider a software in which function A calls function B, which in turn calls function C. If an exception occurs in function C but isn't handled there, the exception is sent to B, who then sends it on to A. Page 2 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics If the issue is not addressed, an error notice appears and our application comes to an abrupt end. Example: Page 3 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: The ZeroDivisionError was triggered in the above example because we were attempting to divide an integer by 0. 1.2 Catching Exceptions in Python When a program is syntactically accurate yet the code produces an error, an exception is thrown. This mistake does not stop the program from running, but it does disrupt the typical flow of the program. Page 4 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Exception using 'try-except': In Python, exceptions are caught and handled using try and except statements. The try clause contains statements that potentially raise exceptions, whereas the except clause contains statements that manage the exception. Example: Page 5 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: Catching Specific Exceptions in Python: We didn't identify any specific exceptions in the except clause in the preceding example. This isn't a smart programming approach because it will capture all exceptions and treat each instance the same. We can indicate which exceptions should be caught with an except clause. If an exception occurs, a try clause can include any number of except clauses to handle distinct occurrences, but only one will be performed. In an except clause, we may declare several exceptions by using a tuple of values. The following is an example of pseudo-code. Page 6 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 7 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: Try with Else Clause: You may utilize the else clause on the try-except block in Python, which must come after all the except clauses. If the try clause does not throw an exception, the function moves to the else block. Page 8 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 9 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: Python ‘try’ with finally clause: Python has a keyword known as ‘finally’ that will always run after the try and except blocks. The finally block is always executed when the try block has terminated normally or has terminated owing to an exception. In some cases, you may wish to run a specific section of code if the code block within the attempt is completed successfully. You can utilize the optional else keyword with the try statement in these circumstances. Page 10 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: Page 11 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: 1.3 Raising an Exception in Python The raise statement allows a programmer to compel the occurrence of a specified exception. raise's only parameter specifies the exception to be raised. This must be an exception instance or a class of exceptions (a class that derives from an Exception). When mistakes occur during runtime, exceptions are thrown. The raise keyword can also be used to manually raise exceptions. We may optionally give values to the exception to provide more information about why it was raised. Page 12 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Example: The output of the preceding code will just be \"An exception,\" but due to the raise statement in the last line, a Runtime error will also occur. As a result, the output on your command line will seem as follows: Page 13 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: 1.4Built-in Exceptions in Python In Python, all instances must be of a class that inherits from BaseException. Even if they have the same name, two exception classes that are not connected via subclassing are never equal. The interpreter or built-in functions can create built-in exceptions. When mistakes occur in Python, a number of built-in exceptions are triggered. The local() built-in methods can be used to inspect these built-in exceptions as follows: >>> locals()['__builtins__'] Page 14 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Base Classes: The exceptions listed below are usually used as basic classes for further exceptions. 1. exception BaseException All built-in exceptions inherit from this base class. It is not intended to be inherited directly by user-defined classes. The exception is used for user- defined classes. This class is in charge of utilizing str() to create a string representation of the exception using the inputs given. If there are no parameters, an empty string is returned. args = The args are the arguments sent to the exception function Object() { [native code] } as a tuple. with_traceback(tb): This technique is commonly used to handle exceptions. This function returns the exception object and sets tb as the new traceback for the exception. 2. exception Exception: This is the basic class for all non-system-exiting exceptions incorporated into the system. This class should be used to derive all user-defined exceptions. 3. exception ArithmeticError: Page 15 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics This is the base class for the built-in exceptions that are thrown when arithmetic mistakes occur, such as OverflowError, ZeroDivisionError, FloatingPointError 4. exception BufferError When buffer-related operations are not possible, this error is thrown. 5. exception LookupError This is the foundation class for exceptions that occur when a mapping or sequence's key or index is incorrect or not found. The exceptions that have been thrown are KeyError and IndexError. Concrete exceptions: The exceptions that are commonly raised are listed below. Exception Description AssertionError Raised when the assert statement fails. AttributeError Raised on the attribute assignment or reference fails. EOFError Raised when the input() function hits the end-of-file condition. FloatingPointError Raised when a floating-point Page 16 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics GeneratorExit operation fails. ImportError IndexError Raised when a generator's close() KeyError method is called. KeyboardInterrupt MemoryError Raised when the imported module is NameError not found. NotImplementedError OSError Raised when the index of a sequence OverflowError is out of range. Raised when a key is not found in a dictionary. Raised when the user hits the interrupt key (Ctrl+c or delete). Raised when an operation runs out of memory. Raised when a variable is not found in the local or global scope. Raised by abstract methods. Raised when a system operation causes a system-related error. Raised when the result of an arithmetic operation is too large to be Page 17 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics ReferenceError represented. RuntimeError Raised when a weak reference proxy StopIteration is used to access a garbage collected referent. SyntaxError IndentationError Raised when an error does not fall TabError under any other category. SystemError SystemExit Raised by the next() function to TypeError indicate that there is no further item to be returned by the iterator. Raised by the parser when a syntax error is encountered. Raised when there is an incorrect indentation. Raised when the indentation consists of inconsistent tabs and spaces. Raised when the interpreter detects internal error. Raised by the sys.exit() function. Raised when a function or operation is applied to an object of an incorrect type. Page 18 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics UnboundLocalError Raised when a reference is made to a local variable in a function or method, UnicodeError but no value has been bound to that UnicodeEncodeError variable. UnicodeDecodeError UnicodeTranslateError Raised when a Unicode-related ValueError encoding or decoding error occurs. ZeroDivisionError Raised when a Unicode-related error occurs during encoding. Raised when a Unicode-related error occurs during decoding. Raised when a Unicode-related error occurs during translation. Raised when a function gets an argument of correct type but improper value. Raised when the second operand of a division or module operation is zero. 1.5File Handling in Python Files are identified places on disc where associated data is stored. They're used to keep data in a non-volatile memory for a long time (e.g. hard disk). Page 19 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics We utilise files for future usage of the data by permanently saving it since Random Access Memory (RAM) is volatile (it loses its contents when the machine is switched off). We must first open a file before we can read from or write to it. When we're finished, it has to be closed so that the file's resources may be released. Python, like many other programming languages, offers file management and allows users to read and write files, as well as perform a variety of other file- related tasks. The notion of file handling has been extended to a variety of other languages, but the implementation is either difficult or lengthy. However, like most Python principles, this concept is simple and straightforward. Python processes files differently depending on whether they are text or binary, which is crucial. Each line of code consists of a series of characters that together constitute a text file. A specific character called the EOL or End of Line character, such as the comma, or newline character, is used to end each line in a file. It signals to the interpreter that the current line has ended and that a new one has begun. Python has built-in file creation, writing, and reading capabilities. In Python, there are two sorts of files that may be handled: text files and binary files (written in binary language, 0s and 1s). Text files: Each line of text in this type of file is concluded with a special character called EOL (End of Line), which in Python is the new line character ('n'). Binary Files: There is no terminator for a line in a binary file, and the data is saved after being converted into machine-understandable binary language. Page 20 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics 1.6File Operations in Python To communicate with the user, we had been accepting input from the terminal and writing it back to the console. It is not always sufficient to just show data on the console. The data to be presented may be huge, and only a limited amount of data may be displayed on the console due to the volatile nature of memory. It is hard to restore the programmatically created data repeatedly. When data must be saved permanently in a file, file management is critical. A file is a designated area on disc where related data can be stored. After the application has terminated, we may retrieve the saved information (non- volatile). The file-handling implementation in the other computer language is significantly longer or more difficult, but it is easier and shorter in Python. Access Modes: The kind of operations that can be performed on the opened file are determined by the access modes. It specifies how the file will be utilised after it has been opened. The File Handle's placement in the file is likewise defined by these modes. A file handle functions similarly to a cursor, indicating where data should be read or written in the file. Python has six different access modes. Read Only ('r'): The handle is at the beginning of the document. If the file does not exist, an I/O error is raised. This is also the default method for opening files. Read and Write ('r+'): Allows you to read and write to a file. The handle is at the beginning of the document. If the file does not exist, an I/O error is thrown. Page 21 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Write Only ('w'): Allows you to write to a file. The data in an existing file is truncated and overwritten. The handle is at the beginning of the document. If the file does not exist, it is created. Write and Read ('w+'): Allows you to read and write to a file. Data is shortened and overwritten for existing files. The handle is at the beginning of the document. Append Only ('a'): Allows you to write to a file. If the file does not exist, it is created. The file's handle is located at the very end. After the current data, the data that is being written will be added at the end. Append and Read ('a+'): Allows you to read and write to a file. If the file does not exist, it is created. The file's handle is located at the very end. After the current data, the data that is being written will be added at the end. Opening a File: The term \"opening a file\" refers to the process of preparing a file for reading or writing. The open() method may be used to do this. This function returns a file object and accepts two parameters, one for the file name and the other for the mode (Access Mode). Example: Page 22 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Page 23 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Output: Reading from a File: A text file may be read in three different ways. read(): returns a string containing the read bytes. Reads n bytes, or the full file if no n is given. Syntax: File_object.read([n]) readline(): reads a single line from a file and returns it as a string. Reads at most n bytes for the provided n. Even if n is more than the length of the line, does not read more than one line. Syntax: File_object.readline([n]) readlines(): Reads all the lines and returns them as a list of string elements, one for each line. Syntax: File_object.readlines() Page 24 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics Writing from a File: A file can be written in one of two ways. write(): The string str1 is inserted in a single line in the text file. Syntax: File_object.write(str1) writelines(): Each string is placed into the text file for a list of string elements. Multiple strings can be inserted at once using this method. Syntax: File_object.writelines(L) for L = [str1, str2, str3] Append to a File: When reading or writing to a file, the access mode determines the kind of operations that may be performed on the file. It specifies how the file will be utilised after it has been opened. The File Handle's placement in the file is likewise defined by these modes. A file handle functions similarly to a cursor, indicating where data should be read or written in the file. Open the file in append mode, with either 'a' or 'a+' as the access mode, to append a new line to an existing file. The following are the definitions of various access modes: Append Only ('a'): This allows you to write to a file. If the file does not exist, it is created. The file's handle is located at the very end. After the current data, the data that is being written will be added at the end. Append and Read ('a+'): This allows you to read and write to a file. If the file does not exist, it is created. The file's handle is located at the very end. After the current data, the data that is being written will be added at the end. Page 25 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics The handle is placed at the end of the file when it is opened in append mode. After the current data, the data that is being written will be added at the end. Closing a File: The close() method terminates a file and releases the memory space it has taken up. It's utilized when the file isn't needed anymore or when it has to be accessed in a different file mode. Syntax: File_object.close() Example: 1.7Summary In this module we have learned: Page 26 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics You can use ‘assert’ to check if a condition is satisfied and throw an exception if it isn't ‘else’ allows you to write sections that should only execute if there are no exceptions in the ‘try’ clause We often utilize a file to store data permanently in secondary storage since it is non-volatile and may be accessed in the future. When you open a file in binary mode, the encoding argument is ignored The rename and remove methods from the ‘os’ module/package can be used to rename and delete files Finally, with or without any previously encountered exceptions, you can run pieces of code that should always run. 1.8Glossary Syntax: It is a collection of rules that governs how a Python program is written and executed. Interpreter: It turns the developer's source code into an intermediate language, which is then translated into the native language/machine language, which is then executed. Runtime error: It arises when a program is syntactically valid but has a problem that is only discovered during execution. Non-volatile memory: Non-volatile memory is memory that keeps its values even if the power is turned off. 1.9References https://docs.python.org/3/ https://docs.python.org/3/tutorial/errors.html https://pythonbasics.org/try-except/ Page 27 of 28 All Rights Reserved. Vol. TLE001/03-2022
Course On Python Basics https://docs.python.org/3/library/exceptions.html https://docs.python.org/3/library/filesys.html https://pythonbasics.org/read-file/ https://pythonbasics.org/write-file/ Page 28 of 28 All Rights Reserved. Vol. TLE001/03-2022
Search
Read the Text Version
- 1 - 28
Pages: