码迷,mamicode.com
首页 > 其他好文 > 详细

异常处理

时间:2019-06-09 18:31:59      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:with open   fun   print   exe   一个   try   异常处理   格式   result   

### 异常处理

#### 基本格式

```python
try:
    pass
except Exception as e:
    pass
```

```python
try:
    v = []
    v[11111] # IndexError
except ValueError as e:
    pass
except IndexError as e:
    pass
except Exception as e:
    print(e) # e是Exception类的对象,中有一个错误信息。
```

```
try:
    int(‘asdf‘)
except Exception as e:
    print(e) # e是Exception类的对象,中有一个错误信息。
finally:
    print(‘最后无论对错都会执行‘)
    
# #################### 特殊情况 #########################
def func():
    try:
        # v = 1
        # return 123
        int(‘asdf‘)
    except Exception as e:
        print(e) # e是Exception类的对象,中有一个错误信息。
        return 123
    finally:
        print(‘最后‘)

func()
```

#### 主动触发异常

```python
try:
    int(‘123‘)
    raise Exception(‘阿萨大大是阿斯蒂‘) # 代码中主动抛出异常
except Exception as e:
    print(e)
```

```python
def func():
    result = True
    try:
        with open(‘x.log‘,mode=‘r‘,encoding=‘utf-8‘) as f:
            data = f.read()
        if ‘alex‘ not in data:
            raise Exception()
    except Exception as e:
        result = False
    return result
```

#### 自定义异常

```python
class MyException(Exception):
    pass

try:
    raise MyException(‘asdf‘)
except MyException as e:
    print(e)
```

```python
class MyException(Exception):
    def __init__(self,message):
        super().__init__()
        self.message = message

try:
    raise MyException(‘asdf‘)
except MyException as e:
    print(e.message)
```

## 

  

异常处理

标签:with open   fun   print   exe   一个   try   异常处理   格式   result   

原文地址:https://www.cnblogs.com/biu-py/p/10994136.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!