Y
Y
Yrets1692021-11-25 23:39:54
Python
Yrets169, 2021-11-25 23:39:54

How to properly wrap in try except?

Good evening, how to enclose the code in a try except block to work correctly?
A code snippet that opens a key in the registry and adds its contents to the list_keys_reg list .
Except in this case works regardless of whether there is such a section in the registry or not.
How to catch the error correctly?

import winreg
list_keys_reg = []
try:
   access_registry = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
   access_key = winreg.OpenKey(access_registry, r"Software\\JavaSoft\\Prefs\\jetbrains")
   i = 0
   while True:
      x = winreg.EnumKey(access_key, i)
      list_keys_reg.append(x)
      i += 1
except:
     print("не удается найти раздел")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yrets169, 2021-11-26
@Yrets169

slightly modified the mikeyuriev code , adding the condition
if 'access_key' in locals(): will be the best option

import winreg

try:
    access_registry = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
    access_key = winreg.OpenKey(access_registry, r"Software\\JavaSoft\\Prefs\\jetbrains")
except OSError:
    print("не удается найти раздел")

if 'access_key' in locals():
    list_keys_reg = []
    i = 0
    while True:
        try:
            x = winreg.EnumKey(access_key, i)
            list_keys_reg.append(x)
            print(list_keys_reg)
            i += 1
        except OSError:
            break

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question