Master Python error handling with try-except blocks, raising exceptions, and creating custom exceptions. Write robust and error-resistant Python programs.
Objective:
Write robust programs by handling errors gracefully using Python’s exception handling mechanisms, ensuring programs run without unexpected crashes.
Topics and Examples:
1. Errors in Python: Syntax vs Runtime
- Syntax Errors: Occur when code violates Python syntax rules.
# SyntaxError example
# print("Hello World" # Missing closing parenthesis
- Runtime Errors: Occur during execution of the program.
# RuntimeError example
num = 10 / 0 # ZeroDivisionError
2. try and except Blocks
try block contains code that may cause an error. except block handles the error gracefully.
Example:
try:
num = int(input("Enter a number: "))
print(10 / num)
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
3. else and finally
elseexecutes if no exception occurs.finallyalways executes, whether an exception occurs or not.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
else:
print(f"Division successful: {result}")
finally:
print("Execution completed")
4. Raising Exceptions Using raise
raise allows you to manually throw exceptions when a condition occurs.
Example:
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print(f"Your age is {age}")
check_age(25) # Valid
# check_age(-5) # Raises ValueError: Age cannot be negative
5. Custom Exceptions
You can create your own exception classes by inheriting from Exception.
Example:
class NegativeNumberError(Exception):
pass
def square_root(num):
if num < 0:
raise NegativeNumberError("Cannot compute square root of a negative number")
return num ** 0.5
try:
print(square_root(-9))
except NegativeNumberError as e:
print(e) # Cannot compute square root of a negative number
This section covers all essential Python exception handling concepts, including different types of errors, try-except-else-finally blocks, raising exceptions, and creating custom exceptions to write robust programs.