Level 9 : Handling exceptions inside a generator.


def safe_gen():
    try:
        yield 1
        1 / 0
        yield 2
    except ZeroDivisionError:
        yield "Error caught"
    yield 3

print(list(safe_gen()))

Author: SandhyaR | Tags: generator | 1859+ Python FAQs | Share
classes | thread | math | oop | quantifiers-(*,-+,-?,-{}) | odd-number | precedence-and-associativity | python-module | precedence | overflow | reading-and-writing-large-files-efficiently | numeric | print-statement | list-mutation | print | operator-overloading | method | list-method | boolean | parameter | typeerror | using-os-and-pathlib-modules | formal-and-actual-parameter | access-modifier | benefit | random | identity-operator | postfix | collections | anchors-(^,-$) | binary | __init_subclass__ | basic | memory-management | function-and-scope | exception-handling | tuple | operator-or | python-django | reading-and-writing-files | operators | floats | type-conversion-and-casting | arbitrary-arguments-(*args,-**kwargs) | binary-operation | reading:-read(),-readline(),-readlines() | built-in-function | floating-point-precision | raise | append | python-history | sorted | while-else-loop | thread-synchronization | array | aggregating-data-with-functools.reduce() | matrix-list-comprehension | bitwise-operator | generators-in-python | opening-files-(open()) | tuple-unpacking | while-loops | error-handling | string-methods | function | built-in | assert | thread-safe-data-structures-(queue.queue) | filter-function | boolean-masking | center | list-methods-and-slicing | min-function | encoding | formatting-with-strftime | methods | command-line-parsing | encapsulation | class-and-instance-variable | zip | using-map()-for-transformations | type_conversion | list-comprehension | bitwise | unit-testing | stack | class-and-inheritance | pickling--unpickling | functional-programming | asyncio-module | while-loop | format | handling-missing-values-(fillna,-dropna) | string-slicing | nested-loop | module | indexing | __future__ | introduction-to-threads | scientific-notation | implementation | type-conversion | objects | turtle | set-operation | match | identifier | set | oops | bitwise-operator | boolean-and-non-boolean | class | class-and-object | file | pep | inheritance | swapping | class-decorators | expand-tab | writing:-write(),-writelines() | math-copysign | __all__-attribute | join | functions | static-method | else-statement | comment | tuples | error | filter | joining-and-merging-dataframes | string-concatenation | namespace | async | integers | regular-expressions | threading | application | using-the-threading-module | with-statement | operator | python-repl | interpreter | attribute | comparison | single-inheritance | strings | version | version-check | arithmetic-operation | assignment-operators | operations | arithmetic-expression | memory | inherit | collection | loop-control | recursion | staticmethod | statement | parsing-with-strptime | slicing | built-in-function | advanced-file-operations | input-function | asyncio | test-discovery | working-with-file-paths | counter-function | syntax-error | overriding-methods | call | conditional-statements | factorial-function | integer | head-and-tail | identity-operators-(is,-is-not) | datetime.date,-datetime.time,-datetime.datetime | booleans | working-with-temporary-files-using-tempfile | namedtuple | zfill-function | logical-operators | descriptors | datetime | list-comprehensions | escape-operator | time-series-with-pandas | literal-characters-and-special-characters | choice | global | object-attribute | random-function | using-else-and-finally | numpy | update | virtual-environment | why-use-multiprocessing-over-threading?-(gil) | pandas | input | heap-memory | dicts | comprehension | list-operation | logical-operation | control-flow | sys-module | difference-between-threads-and-processes | complex-number | data-type | decorator | assignment-operator | syntax | dictionary-methods | decimal | logical-operator | round-function | walking-through-directories-using-os.walk() | multiple-inheritance | recurssion | software-design | string | debugging | loops | loop | copy | creating-and-starting-threads | python-operators | sys | condition | data-structure | complex | data-structures | data-types | string-formatting | name-mangling | compute | tuple-methods | pseudocode | file-handling | working-with-dates-and-times | virtual-environment | indentation | managing-directories-with-os-and-shutil | slice | using-lists-as-stacks | while-and-for-loop | list | exponentiation | lambda-function | multiple-except-blocks | mathematical-function | filtering-and-indexing | keyword | indexing:-loc-vs-iloc | file-handling | intering | iterator | goto-function | list-slicing | library | mysql | list-indexing | global-variable | list-vs-tuple | shallow-copy | string-method | generators | int | string-formatting | global-variable | lambda | else | syntax-error | for | operand | regular-expression | exception | sorting-and-ranking | multiprocessing | feature | string-slicing | expression | iterators | identity-operator | docstring | directory-operations | input-function | introduction-to-python | frozenset | functional-programming | yield | string-method | introduction-to-multiprocessing | list-join | matplotlib | enumerate() | min-max-function | range | list-comprehension | sum() | invalid-list | key-value-pairs | mapping-function | error-handling | fabs-function | polymorphism | dictionaries | syntaxerror | exception-handling | membership-operators-(in,-not-in) | rollback | import-method | type-conversion | using-yield-in-functions | variable | conditional-statement | dictionary | context-manager | deep-copy | zip-function | function-argument | file_handling | generator | global-keyword | gil | init | raise-statement | higher-order-function | using-join()-and-is_alive()-methods | python_version | data-structure | lists | control-flow | logical-operator | list,-set,-and-dictionary-comprehensions | iterable | counter | method-overloading | python-syntax-and-structure | immutability | map-function | data-structures-in-python | return-statement | max-min | package-management | dictionary-comprehensions | string-manipulation | sorting | magic-method | id-function | round | immutable-data-type | lambda-functions | mathematics | conversion | installation | multithreading | constructor | data-type-conversions | using-assertions-(assertequal,-assertraises) | def | multiple-inheritance | lambdas | regex | data_structure | split | control-statement | mutable | touples | loop-control-statements | sets | datatype | conditional-statement | data-type | destructor | operator-and | creating-custom-modules | matrix | python | default-mutable-argument | default-arguments | string-iteration | defining-functions | dataframe-and-series-objects | working-with-binary-files-(rb,-wb) | sum-function | design-principle | built-in-modules | pass ...