Organize Code

Execption

Python

 

Try Except

Python 2.7
def divide(a, b):
  try:
    print(a/b)
  except:
    print("Cannot divide by zero")

Try/Except blocks are used for handling exceptions and errors that can happen in runtime.

Put the risky part of the code inside the try block and specify what to do if an exception happens inside except block.

 

Catch Specific Exception

Python 2.7
def divide(a, b):
  try:
    print(a/b)
  except ZeroDivisionError:
    print("Cannot divide by zero")
  except Exception as e:
    print(e)

You can have multiple except blocks for better error handling.

This helps to run different error handling blocks of code for different types of exceptions.

You can capture multiple exceptions in one exception block.

except (ZeroDivisionError, IOError, RuntimeError):
 

Caught Exception Argument

Python 2.7
def divide(a, b):
  try:
    print(a/b)
  except Exception as e:
    print(e)

Exceptions may have arguments that provide information about that exception.

You can access an exception argument using as keyword.

 

Else

Python 2.7
def divide(a, b):
  try:
    print(a/b)
  except Exception as e:
    print(e)
  else:
    print('No errors')

The else block runs if the try block is executed without any exceptions.

 

Finally

Python 2.7
def divide(a, b):
  try:
    print(a/b)
  except ZeroDivisionError:
    print("Cannot divide by zero")
  except:
    print("Some other error happened")
  finally:
    print("divide function executed")

The code inside the finally block will always be executed after the Try/Except block.

Even if you have a return statement inside a try or catch blocks, the finally block will be run before exiting the method.

 

Raise

Python 2.7
def divide(a, b):
  try:
    raise Exception("Error for no reason")
  except:
    print("Executed all the time")

Exceptions are a great way of organizing your code runtime errors.

If you're writing a Library or any reusable code, you want to raise (throw) different exceptions when different things go wrong, so that the users of your library can do different actions in each case.

Raised exceptions bubble up in the call stack until they are caught.