Python Exceptions

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

A Python program ends as soon as it meets an error. In this Python tutorial, let us see Exceptions and handling with suitable examples.

Introduction of Python Exceptions

When an error occurs, or exception, Python terminates the process and generate an error message.

Those exceptions may be handled using the following statements,

  • try
  • except
  • finally

try-except statement

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

Example

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

note: The try block will generate an exception because x is not defined.

Finally

The “finally” block, if specified, will be executed despite 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.

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.

Leave a Comment

Your email address will not be published. Required fields are marked *