O GoConqr está de visual novo! Conte para nós o que você achou.

Flashcards

033_Exeptions

Serhii Yurskyi Python Advanced Inglês 62 flashcards

Flashcards do conjunto (62)

  1. 1Processing division by zerotry: # Перехватываем исключения
    x = 1 / 0 # Ошибка: деление на 0
    except ZeroDivisionError: # Указываем класс исключения
    print("Обработали деление на 0")
    x = 0
    print(x) # Выведет: 0
  2. 2Nested handlerstry: # Обрабатываем исключения
    try: # Вложенный обработчик
    x = 1 / 0 # Ошибка: деление на 0
    except NameError:
    print("Неопределенный идентификатор")
    except IndexError:
    print("Несуществующий индекс")
    print("Выражение после вложенного обработчика")
    except ZeroDivisionError:
    print("Обработка деления на 0")
    x = 0
    print(x) # Выведет: 0
  3. 3Handling multiple exceptionstry:
    x = 1 / 0
    except (NameError, IndexError, ZeroDivisionError):
    # Обработка сразу нескольких исключений
    x = 0
    print(x) # Выведет: 0
  4. 4Getting exception informationtry:
    x = 1 / 0 # Ошибка деления на 0
    except (NameError, IndexError, ZeroDivisionError) as err:
    print(err.__class__.__name__) # Название класса исключения
    print(err) # Текст сообщения об ошибке
  5. 5An example of using the function exc_info ()import sys, traceback
    try:
    x = 1 / 0
    except ZeroDivisionError:
    Type, Value, Trace = sys.exc_info()
    print("Type: ", Type)
    print("Value:", Value)
    print("Trace:", Trace)
    print("\n", "print_exception()".center(40, "-"))
    traceback.print_exception(Type, Value, Trace, limit=5,
    file=sys.stdout)
    print("\n", "print_tb()".center(40, "-"))
    traceback.print_tb(Trace, limit=1, file=sys.stdout)
    print("\n", "format_exception()".center(40, "-"))
    print(traceback.format_exception(Type, Value, Trace, limit=5))
    print("\n", "format_exception_only()".center(40, "-"))
    print(traceback.format_exception_only(Type, Value))
  6. 6Summing an indefinite number of numbers action with as# -*- coding: utf-8 -*-
    print("Введите слово 'stop' для получения результата")
    summa = 0
    while True:
    x = input("Введите число: ")
    if x == "stop":
    break # Выход из цикла
    try:
    x = int(x) # Преобразуем строку в число
    except ValueError:
    print("Необходимо ввести целое число!")
    else:
    summa += x
    print("Сумма чисел равна:", summa)
    input()
  7. 7Context Manager Protocolclass MyClass:
    def __enter__(self):
    print("Вызван метод __enter__()")
    return self
    def __exit__(self, Type, Value, Trace):
    print("Вызван метод __exit__()")
    if Type is None: # Если исключение не возникло
    print("Исключение не возникло")
    else: # Если возникло исключение
    print("Value =", Value)
    return False # False — исключение не обработано
    # True — исключение обработано
    print("Последовательность при отсутствии исключения:")
    with MyClass():
    print("Блок внутри with")
    print("\nПоследовательность при наличии исключения:")
    with MyClass() as obj:
    print("Блок внутри with")
    raise TypeError("Исключение TypeError")
  8. 8Built-in Exception Classestry:
    x = 1 / 0 # Ошибка: деление на 0
    except ArithmeticError: # Указываем базовый класс
    print("Обработали деление на 0")
  9. 9Catching Exceptionsdef fetcher(obj, index):
    return obj[index]
    x = 'spam'
    try:
    fetcher(x, 4)
    except IndexError: # Catch and recover
    print('got exception')
    print()
    def catcher():
    try:
    fetcher(x, 4)
    except IndexError:
    print('got exception')
    print('continuing')
    catcher()
  10. 10User-defined exception # Raise an instanceclass Bad(Exception):
    pass
    def doomed():
    raise Bad()
  11. 11User-defined exception Catch class nameclass Bad(Exception):
    pass
    def doomed():
    raise Bad()
    try:
    doomed()
    except Bad: # Catch class name
    print('got Bad')
  12. 12User-defined exception class AlreadyGotOneclass AlreadyGotOne(Exception):
    pass # User-defined exception
    def grail():
    raise AlreadyGotOne() # Raise an instance
    try:
    grail()
    except AlreadyGotOne: # Catch class name
    print('got exception')
  13. 13Termination actionsdef fetcher(obj, index):
    return obj[index]
    x = 'spam'
    print('#' * 52 + ' Termination actions')
    try:
    fetcher(x, 3)
    finally: # Termination actions
    print('after fetch')
    fetcher(x, 3)
    def after():
    try:
    fetcher(x, 3)
    finally:
    print('after fetch')
    print('after try?')
    after()
    #
    with open('lumberjack.txt', 'w') as file: # Always close file on exit
    file.write('The newest test!\n')
  14. 14The try_exceptelse Statement# NOTE: the first few snippets from this chapter are not runnable code,
    # but are included in case you wish to expand them into working examples.
    try:
    # Run this main action first
    except :
    # Run if name1 is raised during try block
    except (name2, name3):
    # Run if any of these exceptions occur
    except as :
    # Run if name4 is raised, and get instance raised
    except:
    # Run for all (other) exceptions raised
    else:
    # Run if no exception was raised during try block
  15. 15Catching any and all exceptionstry:
    action()
    except NameError:
    ...
    except IndexError:
    ...
    except KeyError:
    ...
    except (AttributeError, TypeError, SyntaxError):
    ...
    else:
    ...
  16. 16Catching all_ The empty except and Exceptiontry:
    action()
    except NameError:
    ... # Handle NameError
    except IndexError:
    ... # Handle IndexError
    except:
    ... # Handle all other exceptions
    else:
    ... # Handle the no-exception case
    try:
    action()
    except:
    ... # Catch all possible exceptions
    try:
    action()
    except Exception:
    ... # Catch all possible exceptions, except exits
  17. 17Catching Built-in Exceptionsdef kaboom(x, y):
    print(x + y) # Trigger TypeError
    try:
    kaboom([0, 1, 2], "spam")
    except TypeError: # Catch and recover here
    print('Hello world!')
    print('resuming here') # Continue here if exception or not
  18. 18The try_finally Statementtry:
    # Run this action first
    finally:
    # Always run this code on the way out
  19. 19Coding Termination Actions with try_finallyclass MyError(Exception):
    pass
    def stuff(file):
    raise MyError()
    file = open('data', 'w') # Open an output file
    try:
    stuff(file) # Raises exception
    finally:
    file.close() # Always close file to flush output buffers
    print('not reached') # Continue here only if no exception
    #
  20. 20Unified try_except_finallytry: # Merged form
    main-action
    except Exception1:
    handler1
    except Exception2:
    handler2
    ...
    else:
    else-block
    finally:
    finally-block
  21. 21Unified try Statement Syntaxtry: # Format 1
    statements
    except [type [as value]]: # [type [, value]] in Python 2
    statements
    [except [type [as value]]:
    statements]*
    [else:
    statements]
    [finally:
    statements]
    try: # Format 2
    statements
    finally:
    statements
  22. 22Combining finally and except by Nestingtry: # Nested equivalent to merged form
    try:
    main-action
    except Exception1:
    handler1
    except Exception2:
    handler2
    ...
    else:
    no-error
    finally:
    cleanup
  23. 23EXCEPTION RAISED AND CAUGHTtry:
    x = 'spam'[99]
    except IndexError:
    print('except run')
    finally:
    print('finally run')
    print('after run')
  24. 24NO EXCEPTION RAISEDtry:
    x = 'spam'[3]
    except IndexError:
    print('except run')
    finally:
    print('finally run')
    print('after run')
  25. 25NO EXCEPTION RAISED, WITH ELSEtry:
    x = 'spam'[3]
    except IndexError:
    print('except run')
    else:
    print('else run')
    finally:
    print('finally run')
    print('after run')
  26. 26Raising Exceptionsraise IndexError # Class (instance created)
    raise IndexError() # Instance (created in statement)
    exc = IndexError() # Create instance ahead of time
    raise exc
    excs = [IndexError, TypeError]
    raise excs[0]
    try:
    ...
    except IndexError as X: # X assigned the raised instance object
    ...
    class MyExc(Exception): pass
    ...
    raise MyExc('spam') # Exception class with constructor args
    ...
    try:
    ...
    except MyExc as X: # Instance attributes available in handler
    print(X.args)
  27. 27Propagating Exceptions with raisetry:
    raise IndexError('spam') # Exceptions remember arguments
    except IndexError:
    print('propagating')
    raise # Reraise most recent exception
    # propagating
    # Traceback (most recent call last):
    # File "", line 2, in
    # IndexError: spam
  28. 28Trapping Constraints but Not Errorsdef f(x):
    assert x < 0, 'x must be negative'
    return x ** 2
    f(1) # error
    def reciprocal(x):
    assert x != 0 # A useless assert!
    return 1 / x # Python checks for zero automatically
  29. 29The Context Management Protocolclass TraceBlock:
    def message(self, arg):
    print('running', arg)
    def __enter__(self):
    print('starting with block')
    return self
    def __exit__(self, exc_type, exc_value, exc_tb):
    if exc_type is None:
    print('exited normally\n')
    else:
    print('raise an exception!', exc_type)
    return False # Propagate
    with TraceBlock() as action:
    action.message('test 1')
    print('reached')
    with TraceBlock() as action:
    action.message('test 2')
    raise TypeError
    print('not reached')
  30. 30Coding Exceptions Classesclass General(Exception): pass
    class Specific1(General): pass
    class Specific2(General): pass
    def raiser0():
    X = General() # Raise superclass instance
    raise X
    def raiser1():
    X = Specific1() # Raise subclass instance
    raise X
    def raiser2():
    X = Specific2() # Raise different subclass instance
    raise X
    for func in (raiser0, raiser1, raiser2):
    try:
    func()
    except General: # Match General or any subclass of it
    import sys
    print('caught:', sys.exc_info()[0])
  31. 31Coding Exceptions Classesclass General(Exception): pass
    class Specific1(General): pass
    class Specific2(General): pass
    def raiser0(): raise General()
    def raiser1(): raise Specific1()
    def raiser2(): raise Specific2()
    for func in (raiser0, raiser1, raiser2):
    try:
    func()
    except General as X: # X is the raised instance
    print('caught:', X.__class__) # Same as sys.exc_info()[0]
  32. 32Default Printing and Stateraise IndexError # Same as IndexError(): no arguments
    raise IndexError('spam') # Constructor argument attached, printed
    I = IndexError('spam') # Available in object attribute
    I.args
    # ('spam',)
    print(I)
    class E(Exception): pass
    raise E
    raise E('spam')
    I = E('spam')
    I.args
    print(I)
    try:
    raise E('spam')
    except E as X:
    print(X, X.args) # Displays and saves construtor arguments
    # spam ('spam',)
    try:
    raise E('spam', 'eggs', 'ham')
    except E as X:
    print(X, X.args)
  33. 33Custom Print Displays class with __str__ class with __repr__class MyBad(Exception): pass
    try:
    raise MyBad('Sorry--my mistake!')
    except MyBad as X:
    print(X)
    raise MyBad('Sorry--my mistake!')
    class MyBad(Exception):
    def __str__(self):
    return 'Always look on the bright side of life...'
    try:
    raise MyBad()
    except MyBad as X:
    print(X)
    raise MyBad()
    class E(Exception):
    def __repr__(self): return 'Not called!'
    raise E('spam')
    class E(Exception):
    def __str__(self): return 'Called!'
    raise E('spam')
  34. 34Custom Data and Behaviorclass FormatError(Exception):
    def __init__(self, line, file):
    self.line = line
    self.file = file
    def parser():
    raise FormatError(42, file='spam.txt') # When error found
    try:
    parser()
    except FormatError as X:
    print('Error at', X.file, X.line)
  35. 35Custom Data and Behavior 2class FormatError(Exception): pass # Inherited constructor
    def parser():
    raise FormatError(42, 'spam.txt') # No keywords allowed!
    try:
    parser()
    except FormatError as X:
    print('Error at:', X.args[0], X.args[1]) # Not specific to this app
  36. 36Custom Data and Behavior 3class FormatError(Exception):
    logfile = 'formaterror.txt'
    def __init__(self, line, file):
    self.line = line
    self.file = file
    def logerror(self):
    log = open(self.logfile, 'a')
    print('Error at', self.file, self.line, file=log)
    def parser():
    raise FormatError(40, 'spam.txt')
    try:
    parser()
    except FormatError as exc:
    exc.logerror()
  37. 37Control-Flow Nestingdef action2():
    print(1 + []) # Generate TypeError
    def action1():
    try:
    action2()
    except TypeError: # Most recent matching try
    print('inner try')
    try:
    action1()
    except TypeError: # Here, only if action1 re-raises
    print('outer try')
  38. 38Raising errors in Python NotImplementedErrorclass Garage:
    def __init__(self):
    self.cars = []
    def __len__(self):
    return len(self.cars)
    def add_car(self, car):
    # print('this method is a work in progress.') 1.
    raise NotImplementedError("we Can't add cars in to the Garage Yet.")
    ford = Garage()
    ford.add_car('Fiesta')
    print(len(ford))
  39. 39New_errors create class MyCustomErrorclass MyCustomError(TypeError):
    def __init__(self, message, code):
    super().__init__(f'Error code : {code},{message}')
    self.code = code
    raise MyCustomError('OUch! an errer heppend !',500)
  40. 40raiseraise Exception('some error occurred')
  41. 41try_excepttry:
    x = 2 / 0
    except ZeroDivisionError:
    print('Division by zero detected')
  42. 42try_except create class MyExeptionclass MyException(Exception):
    pass
    try:
    raise MyException("error")
    except MyException as e:
    print(e)
    except Exception:
    print('some exception')
  43. 43multiple_exceptions_in_single_clausedef divide_numbers():
    loop = True
    while loop:
    try:
    first_number = float(input('First number: '))
    second_number = float(input('Second number: '))
    print('Result:', first_number / second_number)
    loop = False
    except (ValueError, ZeroDivisionError) as error:
    print('Error:', error)
    print('Please try again')
    print()
    loop = True
    if __name__ == '__main__':
    divide_numbers()
  44. 44default_except_clausetry:
    x = 3 / 0
    except:
    pass
    print('Program flow goes further')
  45. 45unhandled_exceptiontry:
    raise ValueError
    except ZeroDivisionError:
    print('Division by zero')
  46. 46unhandled_exception_in_inner_trytry:
    try:
    raise ValueError('incorrect value')
    except ZeroDivisionError:
    print('division by zero')
    except Exception as e:
    print(e)
  47. 47exception_in_destructorclass MyClass(object):
    def __del__(self):
    raise ZeroDivisionError
    print('Creating object')
    obj = MyClass()
    print('Deleting object')
    del obj
    print('Done')
  48. 48raise_in_excepttry:
    try:
    raise ValueError('value is incorrect')
    except ValueError as error:
    print('Exception:', error)
    raise
    except ValueError:
    print('ValueError detected')
  49. 49raise_another_exception_in_excepta = 5
    b = 0
    try:
    c = a / b
    except ZeroDivisionError:
    raise ValueError
  50. 50raise_froma = 5
    b = 0
    try:
    c = a / b
    except ZeroDivisionError as error:
    raise ValueError('variable b is incorrect') from error
  51. 51raise_from_Nonea = 5
    b = 0
    try:
    c = a / b
    except ZeroDivisionError as error:
    raise ValueError('variable b is incorrect') from None
  52. 52elsedef divide_numbers():
    while True:
    try:
    first_number = float(input('First number: '))
    second_number = float(input('Second number: '))
    result = first_number / second_number
    except (ValueError, ZeroDivisionError) as error:
    print('Error:', error)
    print('Please try again')
    print()
    else:
    print('Result:', result)
    break
    if __name__ == '__main__':
    divide_numbers()
  53. 53finallydef function_that_may_fail():
    response = None
    while response != 'y' and response != 'n':
    response = input('Raise an exception? (y/n) ')
    if response == 'y':
    raise Exception
    try:
    function_that_may_fail()
    except:
    print('Exception handler')
    finally:
    print('Finally block')
  54. 54try-finallytry:
    2 / 0
    finally:
    print('Finally block is always executed')
  55. 55warningsimport warnings
    def input_body_parameter(name, unit, supposed_maximum):
    parameter = float(input('Enter your {} (in {}): '.format(name, unit)))
    if parameter <= 0:
    raise ValueError(name + ' cannot be negative')
    if parameter > supposed_maximum:
    warnings.warn('suspiciously large value of ' + name)
    return parameter
    def input_mass():
    return input_body_parameter(name='mass', unit='kg', supposed_maximum=100)
    def input_height():
    return input_body_parameter(name='height', unit='m', supposed_maximum=2)
    def calculate_bmi(mass, height):
    return mass / (height ** 2)
    def main():
    mass = input_mass()
    height = input_height()
    bmi = calculate_bmi(mass, height)
    print('Your body mass index is', bmi)
    if __name__ == '__main__':
    main()
  56. 56Basic try/excepttry:
    print(1 / 0)
    except:
    print('0!!')
    try:
    print(1 / 0)
    except Exception: # it is almost the same as just `except:`
    print('0!!')
  57. 57Catching specific exceptionstry:
    print(1 / 0)
    except ZeroDivisionError:
    print('Exception!')
  58. 58Catching exception instancetry:
    print(1 / 0)
    except ZeroDivisionError as some_var:
    print('Exception! Stop it!')
    print(some_var)
  59. 59Mismatched exception will not be capturedtry:
    d = {'key': 23}
    print(d['does not exist'])
    except ZeroDivisionError:
    print("This won't be called")
    try:
    d = {'key': 23}
    print(d['does not exist'])
    except KeyError as e:
    print("Got it", e)
  60. 60Raising exceptiontry:
    raise ValueError('Custom message')
    except ValueError as e:
    print('Message is', e)
  61. 61Multiple except blockstry:
    raise ValueError()
    except ZeroDivisionError:
    print('Divided by zero!')
    except AttributeError:
    print('Key is missing!')
    except Exception as ex:
    print("I don't know what's going on!")
    print(ex)
  62. 62try/except/elsetry:
    print('Fine')
    except KeyError:
    print('Nope.')
    else:
    print('Else clause')
    # try/except/finally
    try:
    print(1 / 0)
    except ZeroDivisionError:
    print('0!')
    finally:
    print('I will be called in the end!')
    # All together
    try:
    print('try')
    except ValueError:
    pass # You should never pass on exceptions!
    else:
    print('else')
    finally:
    print('finally')
    try:
    raise ValueError()
    finally:
    print('Finally!')

Informações

Descrição
Advanced Python FlashCards sobre 033_Exeptions, criado por Serhii Yurskyi em 18-09-2019.
Criado por
Serhii Yurskyi
Visualizações
0
Avaliação

Fale Conosco

Sobre o que é sua mensagem?

O que você acha do novo visual?

Você gostou?