# MindSpore在静态图模式下使用try语法报错RuntimeError: Unsupported statement 'Try'.

**1 系统环境**

硬件环境\(Ascend/GPU/CPU\): CPU

MindSpore版本: 1.9.0

执行模式（动态图/静态图）: 静态图

Python版本: 3.7

操作系统平台:linux

**2 报错信息**

2.1 报错信息

```
/root/miniconda3/envs/bin/python /mnt/d/06_project/trouble-shooter/tests/proposer/master/test_compiler_get_context.py
Traceback (most recent call last):
File "/mnt/d/06_project/trouble-shooter/troubleshooter/proposer/proposal_action.py", line 43, in proposal_wrapper
return func(*args, **kw)
File "/mnt/d/06_project/trouble-shooter/tests/proposer/master/test_compiler_get_context.py", line 93, in test2
out = net(input1, input2)
File "/root/miniconda3/envs/lib/python3.7/site-packages/mindspore/nn/cell.py", line 615, in __call__
out = self.compile_and_run(*args)
File "/root/miniconda3/envs/lib/python3.7/site-packages/mindspore/nn/cell.py", line 934, in compile_and_run
self.compile(*inputs)
File "/root/miniconda3/envs/lib/python3.7/site-packages/mindspore/nn/cell.py", line 908, in compile
jit_config_dict=self._jit_config_dict)
File "/root/miniconda3/envs/lib/python3.7/site-packages/mindspore/common/api.py", line 1363, in compile
result = self._graph_executor.compile(obj, args_list, phase, self._use_vm_mode())
RuntimeError: Unsupported statement 'Try'.
More details please refer to syntax support at https://www.mindspore.cn
----------------------------------------------------
- The Traceback of Net Construct Code:
----------------------------------------------------
# In file /root/miniconda3/envs/lib/python3.7/site-packages/mindspore/context.py:462
try:
----------------------------------------------------
- C++ Call Stack: (For framework developers)
----------------------------------------------------
mindspore/ccsrc/pipeline/jit/parse/parse.cc:774 ParseStatement
```

2.2 脚本代码

```
"""
This is a python code template
"""
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.nn import Cell
from mindspore import ops
from mindspore import dtype as mstype
import mindspore

context.set_context(mode=mindspore.GRAPH_MODE, pynative_synchronize=False)

class Net1(nn.Cell):
def __init__(self):
super().__init__()
self.add = ops.Add()
self.sub = ops.Sub()
self.mul = ops.Mul()
self.div = ops.Div()

def func(x, y):
context.get_context("device_target")
return self.div(x, y)

def construct(self, x, y):
a = self.sub(x, 1)
b = self.add(a, y)
c = self.mul(b, self.func(a, b))
return c

def test2():
input1 = Tensor(3, mstype.float32)
input2 = Tensor(2, mstype.float32)
net = Net1()
out = net(input1, input2)
print(out)

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

**3 根因分析**

可能原因: 静态图模式下，网络的construct函数、@ms\_function修饰的函数、@ms.jit修饰的函数中出现如下问题：

1）直接或者间接使用了try语法，此语法静态图模式不支持;

2）直接或间接的调用了MindSpore的get\_context接口（get\_context接口会使用try语法），此接口不能在construct等函数中调用;

补充说明：

此处是间接使用了try语法，mindspore静态图目前不支持try语法，可以参考官网静态图语法支持的链接：

https://www.mindspore.cn/docs/zh-CN/r1.9/note/static\_graph\_syntax\_support.html 里面并没有try语句

而且为什么间接使用了try语法，是因为直接调用get\_context接口，具体可以通过代码查看，

get\_context接口调用了函数\_context（），而\_context（）里面调用了try语法

![](figures/06-123.png)

![](figures/07-124.png)

get\_context\(\) 是在def func（）被调用，def func（）是在def construct\(\)被调用

因此而报错

处理建议:

1）将try语法在函数中移除;

2）函数中调用的get\_context\(\)接口，迁移到函数外调用;

补充说明：

此处由于是间接调用try, 而且try是在mindspore代码里面的

不能修改mindspore代码删除try， 因此就把get\_context\(\)迁移到函数外使用即可

**4 解决方案**

最终方案：

函数中调用的get\_context\(\)接口，迁移到函数外调用;

代码：

```
"""
This is a python code template
"""
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.nn import Cell
from mindspore import ops
from mindspore import dtype as mstype
import mindspore

context.set_context(mode=mindspore.GRAPH_MODE, pynative_synchronize=False)

class Net1(nn.Cell):
    def __init__(self):
        super().__init__()
        self.add = ops.Add()
        self.sub = ops.Sub()
        self.mul = ops.Mul()
        self.div = ops.Div()

    def func(x, y):
        #context.get_context("device_target")
        return self.div(x, y)

    def construct(self, x, y):
        a = self.sub(x, 1)
        b = self.add(a, y)
        c = self.mul(b, self.func(a, b))
        return c

def test2():
    context.get_context("device_target")
    input1 = Tensor(3, mstype.float32)
    input2 = Tensor(2, mstype.float32)
    net = Net1()
    out = net(input1, input2)
    print(out)

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

最终调试结果：

![](figures/08-125.png)

