try01.md 2.0 KB
Newer Older
F
feilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
# Python 异常处理

'a.json'文件不存在,下面代码会有异常,请编写异常控制代码,控制异常的最小范围,出现异常正常打印日志和堆栈

```python
import json
import traceback
import logging
logger = logging.getLogger(__name__)

def load_json(file):
    with open(file, 'r') as f:
        return json.loads(f.read())

def test():
    # TODO(You): 
    ret = load_json('a.json')
    
if __name__ == '__main__':
    test()
```

请选出下列能**正确**实现这一功能的选项。

## template

```python
import json
import traceback
import logging
logger = logging.getLogger(__name__)


def load_json(file):
    with open(file, 'r') as f:
        return json.loads(f.read())


def test():
    try:
        ret = load_json('a.json')
        return {'err': 'success', 'result': ret}
    except Exception as e:
        logger.error(f"load json exception:{str(e)}")
        logger.error(traceback.format_exc())
        return {'err': 'exception'}

if __name__ == '__main__':
    test()
```

## 答案

```python
try:
    ret = load_json('a.json')
    return {'err': 'success', 'result': ret}
except Exception as e:
    logger.error(f"load json exception:{str(e)}")
    logger.error(traceback.format_exc())
    return {'err': 'exception'}
```

## 选项

### A

```python
try:
    ret = load_json('a.json')
    return {'err': 'success', 'result': ret}
except Exception(e):
    logger.error(f"load json exception:{str(e)}")
    logger.error(traceback.format_exc())
    return {'err': 'exception'}
```

### B

```python
try:
    ret = load_json('a.json')
    return {'err': 'success', 'result': ret}
except e:
    logger.error(f"load json exception:{str(e)}")
    logger.error(e.format_exc())
    return {'err': 'exception'}
```

### C

```python
try:
    ret = load_json('a.json')
    return {'err': 'success', 'result': ret}
except Exception as e:
    logger.error(f"load json exception:{str(e)}")
    logger.error(e.format_exc())
    return {'err': 'exception'}
```