Advertisement
makispaiktis

Exceptions

Jul 22nd, 2024
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. # 0. A simple example
  2. while True:
  3.     try:
  4.         x = int(input("Please enter an integer: "))
  5.         break
  6.     except ValueError:
  7.         print("Oops!  That was no valid number.  Try again...")
  8.  
  9.  
  10.  
  11. # 1. Class 'Exception' methods
  12. try:
  13.     raise Exception('spam', 'eggs')
  14. except Exception as inst:
  15.     print(type(inst))       # the exception type
  16.     print(inst.args)        # arguments stored in .args
  17.     print(inst.__str__())   # __str__ allows args to be printed directly, but may be overridden in exception subclasses
  18.     x, y = inst.args
  19.     print('x =', x)
  20.     print('y =', y)
  21.  
  22.  
  23.  
  24. # 2. Multiple Exceptions
  25. import sys
  26.  
  27. try:
  28.     f = open('testfile.txt')                  # Chance for OSError Exception if there is no such file or directory
  29.     s = f.readline()
  30.     i = int(s.strip())                        # Chance for ValueError Exception if s can not be converted into an integer
  31. except OSError as err:
  32.     print("OS error:", err)
  33. except ValueError:
  34.     print("Could not convert data to an integer.")
  35. except Exception as err:
  36.     print(f"Unexpected {err=}, {type(err)=}")
  37.     raise
  38.  
  39.  
  40.  
  41. # 3. Force an Exception to happen
  42. try:
  43.     raise NameError('HiThere')
  44. except NameError:
  45.     print('An exception flew by!')
  46.     # raise
  47.  
  48.  
  49.  
  50. # 4. 'Else' is activated along with 'try', while 'finally' is activated with both 'try' and 'except'
  51. def divide(x, y):
  52.     try:
  53.         result = x / y
  54.     except ZeroDivisionError:
  55.         print("Try clause execution has failed. Division by zero!")
  56.     else:
  57.         print("Else clause is being executed after successful execution of try clause. The result is", result)
  58.     finally:
  59.         print("Finally clause is being executed")
  60.  
  61. divide(2, 1)
  62. divide(2, 0)
  63.  
  64.  
  65.  
  66. # 5. Raising and Handling Multiple Unrelated Exceptions
  67. def f():
  68.     excs = [OSError('Error 1'), SystemError('Error 2')]
  69.     raise ExceptionGroup('There were problems', excs)
  70.  
  71.  
  72. try:
  73.     f()
  74. except Exception as e:
  75.     print(f"Exception caught: {type(e)}: {e}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement