使用finally和函数返回值

编程入门 行业动态 更新时间:2024-10-13 12:17:37
本文介绍了使用finally和函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有代码

private string GetName() { string name = ; 尝试 { name = 这是我的名字; // throw new NotImplementedException(); return 来自try; } catch (例外) { return 错误; } 最后 { name = ; // 清除对象内存。 } 返回名称; }

这个代码中的如果我想返回名字字符串我可以在结尾使用return该函数,但最终运行时,它清除名称值和函数返回空值。 如果我从尝试返回名称比其工作正常,但假设错误进来尝试像我写,然后尝试返回不执行和控制返回到底部,再次给我空白值。 所以,请建议哪种技术最好,为什么。

解决方案

没有解决方案允许:始终使用finally块的返回值,只是因为它在try块的末尾执行 始终 其中发生了什么:捕获与否。 最简单的解决方案是在内部不设置 name finally块:

私人 string GetName() { string name = ; 尝试 { name = 这是我的名字; // throw new NotImplementedException(); } catch (例外) { name = 错误; } 最后 {} return 名称; }

Hi, I have code

private string GetName() { string name = ""; try { name = "This is my name"; //throw new NotImplementedException(); return "from try"; } catch (Exception) { return "Error"; } finally { name = "";//clears object memory. } return name; }

in this code if i want to return name string i can use return in the end of the function but when finally runs, it clears name value and function returns blank value. In case i return name from try than its working fine but suppose error comes in try like i write then this try return not executed and control goes to return at the bottom which gives me blank value again. So , please suggest which technique is best and why.

解决方案

There is no solution that allows that: the return value from the finally block will always be used, simply because it is always executed at the end of the try block regardless of what else happens within it: catch or not. The simplest solution is just to not set name within the finally block:

private string GetName() { string name = ""; try { name = "This is my name"; //throw new NotImplementedException(); } catch (Exception) { name = "Error"; } finally { } return name; }

更多推荐

使用finally和函数返回值

本文发布于:2023-11-26 02:26:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632281.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值   finally

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!