开发者

Android - try/catch question

开发者 https://www.devze.com 2023-03-04 11:45 出处:网络
i have a try/catch in a function that returns a value. if all goes well the return statement in the try block works fine. but what am i supposed to do if theres an exception? what do i return in the c

i have a try/catch in a function that returns a value. if all goes well the return statement in the try block works fine. but what am i supposed to do if theres an exception? what do i return in the catch and finally blocks? the return statement has to be there or the code doesnt compile.

edit: in 1 function i connect to a URL, read a file开发者_如何学Go, and return a string. in another function i open an image from the internet and return a bitmap. so in both of these cases, what am i supposed to have in the return statement at the catch and finally blocks?


One of the following:

  • Return a special value that indicates an error to the calling code.
  • Return a default value (depending on your context, there may not be a good one).
  • Don't catch the exception, instead add a throws to the header.
  • Catch the exception, do the cleanup, and rethrow the exception.

In general, there's no escaping the fact that the function can error out. The calling code must either be notified of that, or the function must effectively swallow an error and pretend nothing bad happened; that involves returning something. The specifics depend on your context...


The value you return should be able to represent an error, for example, null should mean the function didn't work. So, in the catch block, the function would return null, for example. In the finally block, you should free any resource you used (for example, close any files you opened, etc).

You put those things in the finally block because it's guaranteed that it will be ran sometime, even if the code in your catch block throws an unhandled exception or anything. And it will also run if the function worked just as wanted.


Use return null; this statement outside your try/catch block. If the things work, your try block will execute and will return , if it fails because of exception, it will be caught and you will see error.

0

精彩评论

暂无评论...
验证码 换一张
取 消