Python try-except : When you are writing Python programs, sometimes things go wrong. Maybe you tried to open a file that doesn’t exist, or divided a number by zero. 🧨
Without handling these mistakes, your program will crash!
That’s where try-except
comes in — your superhero cape for handling errors gracefully. 🦸♂️
Let’s dive into it — beginner style! 🌟
What is try-except
?
try-except
is a way to tell Python:
“Hey, try to run this code.
But if something goes wrong, don’t crash. Instead, do this other thing.”
Simple, right?
Basic Structure
try:
# code that might cause an error
except:
# code that runs if there is an error
Example 1: Handling Division
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result is: {result}")
except:
print("Oops! Something went wrong.")
✅ If you enter 2
, it prints Result is: 5.0
.
❌ If you enter 0
, it says Oops! Something went wrong.
(because you can’t divide by zero!)
Why Use try-except
?
- Prevent crashing
- Give friendly messages to users
- Handle specific problems differently
Imagine your app crashing just because someone entered a wrong value… Not good! 🙈
Catching Specific Errors
You can catch specific types of errors!
This is more professional and safe.
Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result is: {result}")
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number.")
👉 Now, Python knows what went wrong and responds smartly!
Bonus Tip: else
and finally
You can add two more blocks:
else:
→ Runs if no errors happen.finally:
→ Always runs no matter what.
Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number.")
else:
print(f"Success! The result is {result}")
finally:
print("Thanks for using our calculator!")
✨ Even if there’s an error, finally
will always say “Thanks for using our calculator!” How polite!
Mr. Raj Kumar is a highly experienced Technical Content Engineer with 7 years of dedicated expertise in the intricate field of embedded systems. At Embedded Prep, Raj is at the forefront of creating and curating high-quality technical content designed to educate and empower aspiring and seasoned professionals in the embedded domain.
Throughout his career, Raj has honed a unique skill set that bridges the gap between deep technical understanding and effective communication. His work encompasses a wide range of educational materials, including in-depth tutorials, practical guides, course modules, and insightful articles focused on embedded hardware and software solutions. He possesses a strong grasp of embedded architectures, microcontrollers, real-time operating systems (RTOS), firmware development, and various communication protocols relevant to the embedded industry.
Raj is adept at collaborating closely with subject matter experts, engineers, and instructional designers to ensure the accuracy, completeness, and pedagogical effectiveness of the content. His meticulous attention to detail and commitment to clarity are instrumental in transforming complex embedded concepts into easily digestible and engaging learning experiences. At Embedded Prep, he plays a crucial role in building a robust knowledge base that helps learners master the complexities of embedded technologies.
Leave a Reply