arcgis python add in崩溃_arcgis python 异常处理

try-except语句try-except 语句可用于封装整个程序,或者只封装要捕捉和标识错误的特定代码段。如果 try 语句中发生错误,则会引发异常,然后会执行 except 语句下的代码。使用简单的 except语句是最基本的错误处理方式。

在以下代码中,由于未使用所需的“距离”参数,导致缓冲执行失败。为了在失败之后显示说明性的提示,使用了except 语句来捕捉错误,然后获取并打印缓冲生成的错误消息。请注意,只有在缓冲返回错误后才会执行 except代码块。importarcpytry:#Execute the Buffer tool

# arcpy.Buffer_analysis("c:/transport/roads.shp", "c:/transport/roads_buffer.shp")exceptException as e:printe.message#If using this code within a script tool, AddError can be used to return messages

#back to a script tool. If not, AddError will have no effect.

arcpy.AddError(e.message)try 语句有一个可选的 finally 子句,可用于无论是否出现异常都始终应该执行的任务。下例中,ArcGIS 3D Analyst 扩展模块通过 finally子句检入,从而确保始终会检回该扩展模块。classLicenseError(Exception):pass

importarcpyfrom arcpy importenvtry:if arcpy.CheckExtension("3D") == "Available":

arcpy.CheckOutExtension("3D")else:#Raise a custom exception

# raiseLicenseError

env.workspace= "D:/GrosMorne"arcpy.HillShade_3d("WesternBrook", "westbrook_hill", 300)

arcpy.Aspect_3d("WesternBrook", "westbrook_aspect")exceptLicenseError:print "3D Analyst license is unavailable"

except:print arcpy.GetMessages(2)finally:#Check in the 3D Analyst extension

# arcpy.CheckInExtension("3D")raise语句

上一个示例介绍了如何处理代码中发生的异常;在某些情况下,可能需要创建自定义的异常。此时可使用raise 语句。在以下代码中,在识别出输入要素类未包含任何要素后使用了 raise语句。从严格意义上来说,这并不属于错误,而只是使用代码来预防的一种情况。classNoFeatures(Exception):pass

importarcpyimportos

arcpy.env.overwriteOutput= 1fc=arcpy.GetParameterAsText(0)try:#Check that the input has features

# result =arcpy.GetCount_management(fc)if int(result.getOutput(0)) >0:

arcpy.FeatureToPolygon_management(fc, os.path.dirname(fc)+ os.sep + "out_poly.shp")else:#Raise custom exception

# raiseNoFeatures(result)exceptNoFeatures:#The input has no features

# print fc + "has no features."

except:#By default any other errors will be caught here

# print arcpy.GetMessages(2)

ExecuteError 类

地理处理工具失败时会抛出 ExecuteError 异常类。这说明您可以将错误分成两组,即将地理处理错误(抛出 ExecuteError 异常的错误)归为一组,而将所有其他错误归为一组。然后,可分别采用不同的方式处理这些错误,如下面的代码中所示:importarcpytry:

result= arcpy.GetCount_management("C:/invalid.shp")#Return geoprocessing specific errors#exceptarcpy.ExecuteError:

arcpy.AddError(arcpy.GetMessages(2))#Return any other type of error

except:

arcpy.AddError("Non-tool error occurred")

traceback

在较大较复杂的脚本中,可能很难确定错误的确切位置。可以将 Python 的 sys 和 traceback 模块结合使用来找出错误的准确位置和原因,这种方法可以较为准确地标识出错误的原因并节省您宝贵的调试时间。#Import the required modules#importarcpyimportsysimporttraceback

arcpy.env.workspace= "C:/Data/myData.gdb"

try:

arcpy.CreateSpatialReference_management()#--------------------------

#Your code goes here

# #See the table below for examples

#--------------------------

exceptarcpy.ExecuteError:#Get the tool error messages

#

msgs = arcpy.GetMessages(2)#Return tool error messages for use with a script tool

#arcpy.AddError(msgs)#Print tool error messages for use in Python/PythonWin

#

printmsgsexcept:#Get the traceback object

# tb = sys.exc_info()[2]

tbinfo=traceback.format_tb(tb)[0]#Concatenate information together concerning the error into a message string

# pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])

msgs= "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"

#Return python error messages for use in script tool or Python Window

#arcpy.AddError(pymsg)

arcpy.AddError(msgs)#Print Python error messages for use in Python / Python Window

# print pymsg + "\n"

printmsgs

如果使用了上述代码并且地理处理工具发生了错误(如输入无效),则会引发 ExecuteError,并会使用第一个except 语句。此语句将使用 GetMessages 函数打印出错误消息。如果使用相同的代码但发生的错误类型不同,则会使用第二个 except语句。该语句将获取 traceback 对象并打印出相应的系统错误消息,而不是打印地理处理消息。

下面列出了可替换到上述代码中的三条不同的代码行预计会产生的错误。第一个示例产生了地理处理工具错误,会打印出 traceback 信息和地理处理错误消息。第二个和第三个示例与地理处理并不相关,只会打印 traceback 信息。

代码

产生的错误

arcpy.GetCount_management("")

PYTHON ERRORS:

Traceback info:

File"c:\temp\errortest.py", line 10, in arcpy.GetCount_management("")

Error Info:

Failed to execute. Parameters arenotvalid.

ERROR000735: Input Rows: value isrequired

Failed to execute (GetCount).

ArcPy ERRORS:

Failed to execute. Parameters arenotvalid.

ERROR000735: Input Rows: value isrequired

Failed to execute (GetCount).

x= "a" + 1PYTHON ERRORS:

Traceback info:

File"c:\temp\errortest.py", line 10, in x= "a" + 1Error Info:

cannot concatenate'str' and 'int'objects

float("a text string")

PYTHON ERRORS:

Traceback info:

File"c:\temp\errortest.py", line 10, in float("a text string")

Error Info:

invalid literalforfloat(): a text string

错误结果

从结果对象获取错误消息

有关结果对象的快速表达如下所示:

result= arcpy.GetCount_management("c:/data/rivers.shp")

如果调用 GetCount 引发了异常,则结果对象为空。这表示无法从结果对象中检索错误消息。importarcpytry:

result= arcpy.GetCount_management("c:/data/rivers.shp")#Return GEOPROCESSING specific errors#(this method is INCORRECT!)

except:

arcpy.AddError(result.getMessages(2))

上述代码失败,并显示消息“未定义名称‘result’”。这是由于结果对象因工具失败而无法进行创建。因为未创建结果对象,因此会在尝试使用 getMessages 方法时引发 Python 错误。

注注:即使在工具失败的情况下,也会创建通过调用 ArcGISfor Server 上的地理处理服务所创建的结果对象。仅当工具在本地运行且引发错误时,创建结果对象才会失败。有关使用结果对象的详细信息,请参阅从地理处理工具获取结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值