- Exception handling allows your programs to recovr from errors gracefulls, by using the 4 below we can detect potential issues and build better applications.
1. Try code example
python
try:
x = 10/0
except ZeroDivisionErroe:
print("You can't divide by zero!")
2. Except
python
try:
x = 10/2
except ZeroDivisionError:
print("Division by zero ! ERROR!")
else:
print("Sucessfull division" , x )
finally:
Print("This bloxk will always run!")
3. Else & Finally
4. Catching multiple errors with except
-
Using the exception object, aliased to another name with the *as keyword.
-
here we're using e as an alias for the error object.
try: x = 1/0 except ZeroDivisionError as e: print(f'Error occured : {e}') -
using *e lets you access the actual error message
*4.1
- To catch multiple exceptions in a single except clause by specifying the exceptions as a tupl:
try: number = int(input('Enter a number: ')) result = 10 / number except (ValueError, ZeroDivisionError) as e : print(f'Error occurred: {e}')
- To catch multiple exceptions in a single except clause by specifying the exceptions as a tupl:
Raise Statements
- raise statements allows triggering a manual exception in your code; gives programmer the control over when and how the errors are generated.
- raise statements are mainly used to throw an exception at any point in your program
- here are one of many examples how Python's raise statements could be used
def chech_age(age):
if age < 0 :
raise ValueError('Age cannot be negative')
return age
try:
check_age(-5(
except ValueError as e :
print(f'Error : {e} ') # Error age cannot be neg
-
in this code raise is the keyword which triggers the exception
-
here we're raising a value Error with a custem message when in invalide age is provided
-
re raising the current exception using the raise statement is particularly useful in exception handling
def process_data(data): try: result = int(data) return result * 2 except ValueError: print('Logging : Invalide data received ') raise #Re-raises the same ValueError try: process_data('abc') except ValueError: print('Handled at higher level')- the keyword raise (without arguements) is re-raising the current exception.This allows to log or perform cleanup while still propagating the error up the call stack.