Learn Python
Lesson 1 - Introduction To Python
Lesson 2 - Basic Python Syntax
Lesson 3 - Control Flow
Lesson 4 - Functions
Lesson 5 - Basic Data Structures
Lesson 7 - Modules And Packages
Lesson 8 - Basic String Operations
Lesson 9 - Object-Oriented Programming (OOP)
Exception handling in Python is managed using the try-except
block, where:
try
block encloses the code that might raise an exception.except
block handles specific exceptions that occur within the try
block.For example, if you attempt to divide 10 by 0, it will raise a ZeroDivisionError
. You can handle this error using a try-except
block as shown:
try: result = 10 / 0 print(result) except ZeroDivisionError: print("Cannot divide by zero!")
In this example:
try
block attempts to perform the division 10 / 0
, which raises a ZeroDivisionError
.except
block catches the ZeroDivisionError
and prints a message "Cannot divide by zero!"
.Now, you can modify the divisor (0
) to any other number (e.g., 2
, 5
, 10
) and observe how the program executes without raising a ZeroDivisionError
. For instance:
try: result = 10 / 5 print(result) except ZeroDivisionError: print("Cannot divide by zero!")
In this case, the division operation 10 / 5
will successfully execute, and result
will be 2.0
, which will be printed to the console.