029异常处理
###异常处理
eg1:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 try: 2 inp = input('输入序号:') 3 num = int(inp) 4 except Exception as e: 5 print(e) 6 num = 1 7 8 print(num)
eg2:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 try: 2 li = [11,22] 3 a = li[3] 4 except IndexError as e: 5 print(e) 6 except ValueError as e: 7 print('ValueError',e) 8 except Exception as e: 9 print('Exception',e) 10 else: 11 print('else') # 不出错执行else里面的 12 finally: 13 print('一定会执行') # 一定会执行
对于各种错误类型,写入到不同的日志文件,所以需要抓取不同的错误进行不同的操作
##主动触发异常
try里面写raise Exception()
主要也是用于日志记录
eg:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class OldBoyError(Exception): 2 def __init__(self,msg): 3 self.message = msg 4 def __str__(self): 5 return self.message 6 7 try: 8 raise OldBoyError('想') 9 except OldBoyError as e: 10 print(e)
##assert 断言
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
print(213) assert 1 == 2 # 1不等于2,这里不满足,就不会进行下面的。 print(456)
可以捕获,也可以不捕获。强制用户满足某个条件
一些打的代码会通过编辑重新加入,目的是熟悉知识,熟悉代码
1、摄氏度转华氏度
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.util.Scanner; 2 3 public class CelsiusConverter 4 { 5 public double get_fahrenheit(double celsius){ 6 double fahrenheit = 1.8 * celsius + 32; 7 return fahrenheit; 8 } 9 public static void main(String[] args) 10 { 11 System.out.print("输入你要转换的温度(摄氏度):"); 12 Scanner in = new Scanner(System.in); 13 double celsius = in.nextDouble(); 14 CelsiusConverter celsius_converter = new CelsiusConverter(); 15 double fahrenheit = celsius_converter.get_fahrenheit(celsius); 16 System.out.println("华氏度为:" + fahrenheit); 17 } 18 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # __author: _nbloser 2 # date: 2018/1/22 3 4 class CelsiusConverter: 5 def get_fehrenheit(self, celsius): 6 try: 7 fehrenheit = 1.8 * float(celsius) + 32 8 except Exception as e: 9 fehrenheit = 'error' 10 return fehrenheit 11 12 13 if __name__ == '__main__': 14 celsius = input('输入摄氏度:') 15 celsius_converter = CelsiusConverter() 16 fehrenheit = celsius_converter.get_fehrenheit(celsius) 17 print('华氏度:', fehrenheit)