🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Python Notes
Topic #97

Python Try...Except


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.


Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement:

Example

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

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example

print(x)

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:

Example

try:
  print(x)
except NameError:
  print("Variable x
is not defined")
except:
  print("Something else went
wrong")

See more Error types in our Python Built-in Exceptions Reference.


Else

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

Example

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

Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

Example

try:
  print(x)
except:
  print("Something went
wrong")
finally:
  print("The 'try except' is finished")

This can be useful to close objects and clean up resources:

Example

try:
  f = open("demofile.txt")
  try:

f.write("Lorum Ipsum")
  except:

print("Something went wrong when writing to the file")
  finally:

f.close()
except:
  print("Something went wrong when opening the
file")

The program can continue, without leaving the file object open.


Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below
zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example

x = "hello"

if not type(x) is int:
  raise TypeError("Only
integers are allowed")

Want to go beyond the notes?

Join CodingNow 2.0's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Python Try...Except – FAQs

Quick answers about learning Python Try...Except in Python.

This free note from CodingNow 2.0 explains Python Try...Except in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on CodingNow 2.0, including Python Try...Except, is 100% free with no signup required.
With focused practice, most students grasp Python Try...Except in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now