Skip to main content

Python Exception Handling

Python Exception Handling is a core Python concept covering python Exception Handling: --8<-- "core-logic/exception-handling.md" This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.

Exception Handling: Dealing with Errors

In programming, an Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Essentially, it's a "crash" or an "error."

Why handle Exceptions?

  1. Prevent Crashing: If an error occurs (like dividing by zero), you don't want the whole program to just stop.
  2. User Experience: Instead of a cryptic computer error, you can show a friendly message (e.g., "Please enter a valid number").
  3. Cleanup: Ensure that things like files or database connections are closed even if an error occurs.

The "Try-Catch" Logic

  • Try: "Try running this code."
  • Catch/Except: "If an error happens, do this instead."
  • Finally: "No matter what happens, always do this at the end."
Logic First

Exception handling is about defensive programming. You are anticipating what could go wrong and providing a safety net.

Try ... Except

The try block lets you test a block of code for errors. The except block lets you handle the error.

try:
print(x)
except:
print("An exception occurred")

Since the variable x is not defined, the program will jump to the except block instead of crashing.

The else Keyword

You can use the else keyword to define a block of code to be executed if no errors were raised:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Specific Exceptions

It's better to catch specific errors rather than a general except:.

try:
# code
except ZeroDivisionError:
print("You cannot divide by zero!")

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir