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