1) Introduce try / except
try: # Code that might cause an error x = int(input("Please enter a number: ")) y = 1/x print(y) except ValueError: # Handle ValueError exception print("Error: You must enter a valid number.") except ZeroDivisionError: # Handle ZeroDivisionError exception print("Error: Cannot divide by zero.") except: # Handle all other exceptions print("Unknown error occurred.")
The try block contains code that might cause an exception. If an exception occurs in the try block, Python will jump to the except block that matches the exception.
We have three except blocks to handle different exception types:
- ValueError will be triggered if int() fails to convert the input to a number
- ZeroDivisionError will occur if x is 0
- The blanket except will catch any other exceptions not caught above
The advantage of try-except is that we can gracefully handle errors and continue program execution instead of crashing. We can also print custom error messages for the user.
To summarize:
- Put risky code in try block
- Catch anticipated exceptions in except blocks
- Print error messages to notify user
- Use except: to catch general errors
- Program continues despite exceptions
This allows our program to continue running instead of terminating on an error.
2) Use else finally in python
try: x = int(input("Please enter a number: ")) y = 1/x except ValueError: print("Error: You must enter a valid number.") except ZeroDivisionError: print("Error: Cannot divide by zero.") else: print(f"1/{x} is {y}") # Executes if no exceptions finally: print("Executing finally block")
The else block executes only if no exceptions occur in the try block. This is useful for code that should run if everything succeeded.
The finally block always executes after the try and except blocks, even if an exception occurred. This is useful for cleanup code like closing files or network connections.
3) How to find out the value exception on production
There are a few good ways to get exception details when running an application in production:
- Log exceptions to file
import logging try: # risky code except Exception as e: logging.error(e, exc_info=True)