Try and Exception in Python

Try and Exception in Python

  • Exception is the error and is an event, which occur when program statements are executing.

  • It disrupts the flow of program’s statements.

  • Exception is the run time error when occur, further program is not execute.

Exception List

StopIteration

SystemExit

StandardError

ArithmeticError

OverflowError

FloatingPointError

ZeroDivisionError

AssertionError

AttributeError

EOFError

ImportError

KeyboardInterrupt

LookupError

IndexError

KeyError

NameError

UnboundLocalError

EnvironmentError

IOError

SyntaxError

IndentationError

SystemError

SystemExit

TypeError

ValueError

RuntimeError

NotImplementedError

Exception Handling: try except else and finally:

try: Used to test a code or to try a code whether it give error or not.

except: Used to handle a error

else: Used to execute code when code is error free

finally: It execute a code after try except and /or else part. It does not mean with raising error or not. It will excecute when try except to end. 

Example: try except

Example with any exception:

try:

  print(name)

except:

  print(“Exception will be raise, because name is not defined")

Specify only one exceptions

try:

  print(3/0)

except ZeroDivisionError:

  print(“You are dividing with zero, that is error")

Specify multiple exceptions

try:

  print(3/0)

except ZeroDivisionError:

  print(“You are dividing with zero, that is error")

except SyntaxError:

  print(“There is syntax error”)

except:

  print(“There is another error occurred”)

Example: try except and else

Example with any exception:

try:

  print(name)

except:

  print(“Exception will be raise, because name is not defined")

Else:

  print(“Not a error because variable is defined”)

Example: try except else and finally

Example with any exception:

try:

  print(name)

except:

  print(“Exception will be raise, because name is not defined")

else:

  print(“Not a error because variable is defined”)

finally:

  print(“Code is completed”)

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics