Page 453 - CITS - Computer Software Application -TT
P. 453

COMPUTER SOFTWARE APPLICATION - CITS

            Exception Handling


           Exception handling in Python allows you to gracefully manage errors or exceptional situations that may occur
           during the execution of your code. Python provides a way to catch and handle these exceptions using ‘try’,
           ‘except’, ‘else’, and ‘finally’ blocks.
           Here’s an overview of each component:
           •  try: The ‘try’ block is used to enclose the code that might raise an exception.
           except: The ‘except’ block is used to catch and handle specific exceptions that occur within the corresponding ‘try’
           block. You can specify the type of exception you want to handle, or you can use a generic ‘except’ block to catch
           any exception.

           else: The ‘else’ block is executed if no exceptions occur in the ‘try’ block. It is optional.
           finally: The ‘finally’ block is used to execute cleanup code that should be run regardless of whether an exception
           occurred. It is executed whether an exception occurred or not. It is optional.

           Here’s a basic example demonstrating how to use exception handling in Python:









































           In this example:
           The ‘try’ block contains code that prompts the user to enter a number, performs a division operation, and prints
           the result.

           The ‘except’ blocks handle specific exceptions (‘ZeroDivisionError’ and ‘ValueError’) that may occur within the try
           block.
           The ‘else’ block prints a message if no exceptions occur.
           The ‘finally’ block prints a message indicating that the execution is complete, regardless of whether an exception
           occurred or not.
           Exception handling  allows  your program to recover from errors gracefully, ensuring  that it doesn’t crash
           unexpectedly and providing feedback or alternative paths when errors occur.




                                                           440

                             CITS : IT&ITES - Computer Software Application - Lesson 120 - 137
   448   449   450   451   452   453   454   455   456   457   458