python初学者Traceback (most recent call last):

如题所述

1、打开Python开发工具IDLE,新建‘myexcept.py’文件,并写代码如下:

classmyException(Exception):

def__init__(self,error):

self.error=error

def__str__(self,*args,**kwargs):

returnself.error

这就是自定义定义的异常类,继承自Exception父类,有error字段,__str__函数的作用是打印对象时候,显示的字符串

2、继续写代码,抛出异常,代码如下:

classmyException(Exception):

def__init__(self,error):

self.error=error

def__str__(self,*args,**kwargs):

returnself.error

raisemyException('自定义异常')

3、F5运行程序,在Shell中打印出异常:

Traceback(mostrecentcalllast):

  File "C:/Users/123/AppData/Local/Programs/Python/Python36/myexcept.py", line 7, in <module>

raisemyException('自定义异常')

myException:自定义异常

4、下面做测试来捕获这个异常,代码如下;

classmyException(Exception):

def__init__(self,error):

self.error=error

def__str__(self,*args,**kwargs):

returnself.error

try:

a=0

b=1

ifa!=b:

raisemyException('自定义异常')

exceptmyExceptionase:

print(e)

5、F5运行程序,在Shell中打印出捕获到异常的信息:自定义异常

6、也可以直接用Exception来捕获,代码如下:

classmyException(Exception):

def__init__(self,error):

self.error=error

def__str__(self,*args,**kwargs):

returnself.error

try:

a=0

b=1

ifa!=b:

raisemyException('自定义异常')

exceptExceptionase:

print(e)

7、F5运行程序,在Shell中打印出捕获到异常的信息:自定义异常

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-07-26
把 raw_input 改成 input ,再试试。
Python3将raw_input和input进行整合成了input....去除了raw_input()函数....
其接受任意输入, 将所有输入默认为字符串处理,并返回字符串类型本回答被提问者采纳
第2个回答  2019-07-26
python 2中 row_input( ) 和 input( ) 都可用作接受输入
Python3.x 中 raw_input( ) 和 input( ) 进行了整合,去除了 raw_input( ),仅保留了 input( ) 函数
所以建议你使用input代替
相似回答