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