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