Skip to content

Latest commit

 

History

History
31 lines (29 loc) · 2.08 KB

Errors and Exceptions.md

File metadata and controls

31 lines (29 loc) · 2.08 KB

Errors and Exceptions

#python

Apart from SyntaxError, which is related to untenable Python code, the interpreter throws a variety of exceptions as indicators of errors. Some examples include ZeroDivisionError, NameError, etc. Standard exception names, such as these, in Python, are built-in identifiers, but not reserved keywords. Exceptions usually provide a traceback including the line causing the error, the line number, and the file name which can be useful for debugging.

Exceptions generated by Python can be handled using the try and except construct.

try: 
	f = open('myfile.txt')
except OSError as err:
	print("OS error:", err)
except (ValueError, NameError):
	print("An exception")
	raise ValueError("This is also a NameError")
except TypeError as err:
	raise OSError from err
else:
	f.close()
finally:
	...
  • A try statement can have more than one except clause. Moreover, exceptions can be bundled together as a tuple.
  • At most, one handler will be executed which is the first matching except clause.
  • While writing exception clauses, it is best to be as specific as possible so that unexpected exceptions can be propagated on.
  • try...except has an optional else clause which, when used, must be placed after all except clauses and is useful for code that must be executed if the try clause does not raise an exception.
  • The raise statement allows an optional from clause which is useful when transforming exceptions.
  • The try statement has another optional clause called finally which is used to define clean-up actions that must be executed under all circumstances.
    • Unhandled exceptions, or exceptions raised by the except statement are re-raised after the execution of the finally statement.
    • If finally contains a break, continue, or return, then unhandled exceptions are not re-raised.
    • If the try statement has a break, continue, or return statement, the finally clause will execute prior to these statements.
    • If both finally and try contain a return statement, then the return of finally will take precedence.