|
| 1 | +# Exception handling in Python allows you to handle errors that may occur during the execution of your code. By using exception handling, you can ensure that your code continues to run even if an error occurs. |
| 2 | + |
| 3 | +# Here's the basic syntax for exception handling in Python: |
| 4 | + |
| 5 | + |
| 6 | +# try: |
| 7 | +# # code that may raise an exception |
| 8 | +# except ExceptionType as variable: |
| 9 | +# # code to handle the exception |
| 10 | + |
| 11 | + |
| 12 | +# The try block contains the code that may raise an exception. |
| 13 | +# The except block contains the code to handle the exception if it occurs. ExceptionType is the type of exception you want to catch, such as ValueError, TypeError, etc. variable is a variable that will contain the exception object if an exception occurs. |
| 14 | +# You can have multiple except blocks to handle different types of exceptions. |
| 15 | + |
| 16 | +# For example: |
| 17 | + |
| 18 | +try: |
| 19 | + num = int(input("Enter a number: ")) |
| 20 | +except ValueError: |
| 21 | + print("Invalid input. Not a number.") |
| 22 | +# This code tries to convert the input from the user to an integer. |
| 23 | +# If the input is not a valid number, a ValueError exception will be raised, |
| 24 | +# and the code in the except block will be executed to handle the exception. |
| 25 | + |
| 26 | +# You can also use the finally block to specify code that must be executed |
| 27 | +# whether an exception occurs or not. The syntax for using a finally block is: |
| 28 | + |
| 29 | +# try: |
| 30 | +# # code that may raise an exception |
| 31 | +# except ExceptionType as variable: |
| 32 | +# # code to handle the exception |
| 33 | +# finally: |
| 34 | + # code to be executed regardless of whether an exception occurred |
| 35 | + |
| 36 | +# For example: |
| 37 | + |
| 38 | +try: |
| 39 | + num = int(input("Enter a number: ")) |
| 40 | +except ValueError: |
| 41 | + print("Invalid input. Not a number.") |
| 42 | +finally: |
| 43 | + print("This code will always be executed.") |
| 44 | +# In this code, the finally block will always be executed, even if an exception |
| 45 | +# occurs in the try block. |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +# https://youtube.com/@codewithmuh |
| 51 | +# https://github.com/rashiddaha |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | + |
0 commit comments