Exception Handling

Types of Errors

(i)Compile-time errors. These are the errors resulting out of violation of programming language’s grammar rules. All syntax errors are reported during compilation.

(ii) Run-time errors. The errors that occur during runtime because of unexpected situations. Such errors are handled through exception handling routines of Python.

Syntax Error

These are the errors resulting out of violation of programming language’s grammar rules. All syntax errors are reported during compilation. Example:

Exception

Exceptions are unexpected events or errors that occur during the execution of a program, such as a division by zero or accessing an invalid memory location. These events can lead to program termination or incorrect results.

       “It is an exceptional event that occurs during runtime and causes normal program flow to be disrupted.”

Observe that there is nothing wrong with the program syntax, it is only when we try to divide an integer with zero , an exception is generated.

Exception (Examples):

Only When we are trying to access a list element with an non existing index an exception is generated.

Only When we are trying to convert a string to integer the Exception generated.

What is Exception Handling?

Exception handling in Python is a mechanism used to handle runtime errors that occur during the execution of a Python program

Exception handling allows a program to gracefully handle such exceptions and recover from errors by taking corrective actions instead of terminating abruptly. In Python, exception handling is implemented using a try-except block

Exception Handling using. try and except Block:

The try and except block in Python is a way to handle exceptions or errors that may occur during code execution. This mechanism prevents the program from crashing by allowing it to continue running even if an error is encountered.

In a try block, you write the code that might raise an exception. If an exception occurs, the code execution jumps to the corresponding except block, where you can handle the error or take alternative actions.

Exception (Example-1):

Exception (Example-1):

Write a program to ensure that an integer is entered as input and in case any other value is entered, it  displays a message – ‘Not a valid integer’

General Built-in Python Exceptions:

Exception NameDescription
EOFErrorRaised when one of the built-in functions (input( )) hits an end-of-file condition (EOF) without reading any data. (NOTE. the file.read( ) and file.readline( ) methods return an empty string when they hit EOF.)
IO ErrorRaised when an I/O operation (such as a print statement, the built-in open( ) function or a method of a file object) fails for an I/O-related reason, e.g., “file not found” or “disk full”.
NameErrorRaised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.
IndexErrorRaised when a sequence subscript is out of range, e.g., from a list of length 4 if you try to read a value of index like 8 or E8 etc. (Slice indices are silently truncated to fall in the allowed range ; if an index is not a plain integer, TypeError is raised.)
ImportErrorRaised when an import statement fails to find the module definition or when a from … import fails to find a name that is to be imported.
TypeErrorRaised when an operation or function is applied to an object of inappropriate type, e.g., if you try to compute a square-root of a string value. The associated value is a string giving details about the type mismatch.
ValueErrorRaised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
ZeroDivisionErrorRaised when the second argument of a division or modulo operation is zero.
OverflowErrorRaised when the result of an arithmetic operation is too large to be represented.
KeyErrorRaised when a mapping (dictionary) key is not found in the set of existing keys
ImportErrorRaised when the module given with import statement is not found.
KeyboardInterruptRaised when keys Esc, Del or Ctrl+C is pressed during program execution and normal program flow gets disturbed.
Built-in Python Exceptions

Second Argument of the Exception Block:

We  can also provide a second argument (optional) for the except block, which gives a reference to the exception object.

Handling Multiple Errors

Handling multiple exceptions in Python allows a single try-except block to handle different types of exceptions using multiple except blocks. This allows a program to handle various types of errors that may occur during runtime and take corrective measures accordingly.

In a try-except block, each except block is associated with a specific exception type, and the block containing the code to handle that exception is executed if the corresponding exception occurs in the try block. By handling multiple exceptions, programmers can write more robust and less error-prone code.

Syntax:

Example: Program to handle multiple exceptions:

Execution Order:

The <try suite> is executed first ; if, during the course of executing the <try suite>, an exception is raised that is not handled otherwise, and  the <except suite> is executed, with <name> bound to the exception, if found ; if no matching except suite is found then unnamed except suite is executed.

finally Block

The finally block is a part of the try-except block in Python that contains the code that is executed regardless of whether an exception is raised or not. The syntax of the try-except-finally block is as follows:

the try block contains the code that may raise an exception. If an exception occurs, the control is transferred to the corresponding except block, which contains the code to handle the exception. The finally block contains the code that is executed after the try-except blocks, regardless of whether an exception occurred or not.

Example :Program using finally block

Example :Program using finally an else block together

In this example, if the user enters an invalid input or attempts to divide by zero, the corresponding except block handles the exception and prints an error message to the user. If no exception occurs, the else block is executed and prints the result. Finally, the finally block is executed and prints a message to indicate the completion of the program execution.

Practice Programs

1. Write a Python program that takes two numbers as input from the user and calculates the quotient of the two numbers. Handle the exceptions that may occur during the program execution, such as invalid input or division by zero.

2. Write a Python program that reads a file and displays its contents on the screen. Handle the exceptions that may occur during the program execution, such as the file not found error or file reading error.

3. Write a Python program that takes a list of integers as input from the user and calculates the average of the numbers. Handle the exceptions that may occur during the program execution, such as invalid input or division by zero.

4. Write a Python program that reads a CSV file and displays its contents on the screen. Handle the exceptions that may occur during the program execution, such as the file not found error or file reading error.

5. Write a Python program that takes a string as input from the user and converts it to an integer. Handle the exceptions that may occur during the program execution, such as invalid input or string conversion error.

6. Write a Python program that takes a list of numbers as input from the user and finds the maximum and minimum numbers in the list. Handle the exceptions that may occur during the program execution, such as invalid input or empty list error.

7. Write a Python program that reads a file and writes its contents to another file. Handle the exceptions that may occur during the program execution, such as the file not found error or file reading/writing error.

8. Write a Python program that takes two strings as input from the user and concatenates them. Handle the exceptions that may occur during the program execution, such as invalid input or string concatenation error.

9. Write a Python program that reads a text file and counts the number of words in it. Handle the exceptions that may occur during the program execution, such as the file not found error or file reading error.

10. Write a Python program that takes a string as input from the user and reverses it. Handle the exceptions that may occur during the program execution, such as invalid input or string reversal error.