Try Except

  • Try and Except statement is used to handle the errors within our code in Python.
  • The try except statement can handle exceptions. 

Syntax

try:

  # Some Code

except:

  # Executed if error in the # try block

Finally:

  #always executed

Python Try Except

  • The try block lets you test a block of code for errors.
  • The except block lets you handle the error.
  • The finally block lets you execute code, regardless of the result of the try- and except blocks.

What are exceptions in Python?

  • If an error occurs while running the program, it’s called an exception.
  • If an exception occurs, the type of exception is shown.
  • Some exceptions you may have seen before are FileNotFoundError, ZeroDivisionError or ImportError but there are many more.

Why?

  • 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:

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

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

This statement will raise an error, because x is not defined:

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:

try:

    f = open('missing')

    except OSError:

        print('It failed')

    except FileNotFoundError:

        print('File not found')

Else Block

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")

Finally Block

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

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

Raise an exception

  • To throw (or raise) an exception, use the raise keyword.
  • Raise an error and stop the program if x is lower than 0:
x = -1

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

0 Comments

Leave a Reply

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