print(55/0)
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-1-ef255b193978> in <module>() ----> 1 print(55/0) ZeroDivisionError: division by zero
alist = []
print(alist[0])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-2-d994a3a20fe2> in <module>() 1 alist = [] ----> 2 print(alist[0]) IndexError: list index out of range
atup = ('a', 'b', 'c')
atup[0] = 'A'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-8aeda75553d6> in <module>() 1 atup = ('a', 'b', 'c') ----> 2 atup[0] = 'A' TypeError: 'tuple' object does not support item assignment
try: # statement(s) thay may potentially throw(s) exception except ExceptionName1: # catch specific exception ExceptionName1 # statement(s) to handle the exception [except ExceptionName2 as err: # statements ] [except: # catch any error not caught by previous except blocks ] [else: # follows all except clause # executes if try clause does NOT raise an exception ] [finally: # clean-up actions that must be executed under all circumstances; # exectued on the way out when try block is left via a break, continue, or return statement ]
try:
x = int(input("Enter dividend: "))
y = int(input("Enter divisor: "))
quotient = x/y
remainder = x%y
except ZeroDivisionError as ex:
print('Exception occured:', ex)
print('arguments:', ex.args)
except:
print('Some exception occured...')
else:
print("quotient=", quotient)
print("remainder=", remainder)
finally:
print("executing finally clause")
Enter dividend: 10 Enter divisor: 2 quotient= 5.0 remainder= 0 executing finally clause
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was not a valid number. Try again...")
Please enter a number: f Oops! That was not a valid number. Try again... Please enter a number: dsaf Oops! That was not a valid number. Try again... Please enter a number: adsf Oops! That was not a valid number. Try again... Please enter a number: asdf Oops! That was not a valid number. Try again... Please enter a number: 10
raise NameError("MyException")
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-8-290333e3086c> in <module>() ----> 1 raise NameError("MyException") NameError: MyException
try:
raise NameError('My Exception')
except NameError:
print('An exception flew by...')
raise
An exception flew by...
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-9-9b6ca7775e88> in <module>() 1 try: ----> 2 raise NameError('My Exception') 3 except NameError: 4 print('An exception flew by...') 5 raise NameError: My Exception
class InputError(Exception):
"""
Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occured
message -- explaination of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
help(InputError)
Help on class InputError in module __main__: class InputError(builtins.Exception) | Exception raised for errors in the input. | | Attributes: | expression -- input expression in which the error occured | message -- explaination of the error | | Method resolution order: | InputError | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, expression, message) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from builtins.Exception: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __delattr__(self, name, /) | Implement delattr(self, name). | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | helper for pickle | | __repr__(self, /) | Return repr(self). | | __setattr__(self, name, value, /) | Implement setattr(self, name, value). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
def getInteger():
x = input('Enter an integer number: ')
if not x.isdigit():
raise InputError(x, 'That is not an integer!')
return int(x)
x = getInteger()
print(x)
Enter an integer number: dsaf
--------------------------------------------------------------------------- InputError Traceback (most recent call last) <ipython-input-15-f90a077ee9cc> in <module>() ----> 1 x = getInteger() 2 print(x) <ipython-input-14-6a80b90df6da> in getInteger() 2 x = input('Enter an integer number: ') 3 if not x.isdigit(): ----> 4 raise InputError(x, 'That is not an integer!') 5 return int(x) InputError: ('dsaf', 'That is not an integer!')