Pythondex

Tutorial

Try & Except

Sometimes, your Python code can cause errors while running. These are called exceptions. To handle them and avoid crashes, Python provides try and except blocks.

Using Try & Except

The try block contains the code that might cause an error. The except block contains code that runs if an error occurs.

  • If the user enters 0, the ZeroDivisionError is caught.
  • If the user enters something that's not a number, ValueError is caught.
  • The program will not crash, and you see a friendly message instead.

Handling Multiple Exceptions in One Line

You can handle multiple exceptions using a tuple in a single except:

Using Else

The else block runs only if there is no exception:

Using Finally

The finally block always runs, even if an exception occurs:

Common Exceptions

  • ZeroDivisionError – dividing by zero
  • ValueError – wrong type of input
  • FileNotFoundError – trying to open a missing file
  • TypeError – performing an invalid operation on a type

What You Learned

  • Exceptions are errors that occur during program execution.
  • try lets you test code that might fail.
  • except handles specific errors safely.
  • else runs if no exception occurs.
  • finally always runs, useful for cleanup.
  • Handling exceptions prevents your program from crashing and allows graceful messages.