Throw exception when file not found, in mathematica
I have a function that processes an image whose path is given by the user. I'm a bit new to Mathematica, and I can't find much on its large documentation. How can I throw an exception when Import[myFile] fa开发者_运维百科ils? Can I even do that?
Thanks a lot.
A simple prototype is
Catch[
Check[img = Import["myFile"], Throw[$Failed], Import::nffil];
Print["Processing image"]
]
Where you can make the Catch
and Throw
more targeted by using tag
s if need be.
You can use Throw[anyExpression]
or Throw[anyExpression, exceptionTag]
to throw an exception, with any expression. You can then use Catch[your code]
or Catch[yourCode,exceptionPattern]
. Exceptions in Mathematica are not objects like in e.g. Java, so you can not directly use the technique of building exception inheritance hierarchies and use multiple catch statements to catch from more specific to more general. Exception tags are needed to give an exception an identity, somewhat similar to exception class name in Java. Throw
without a second argument will throw an untagged exception, which can be caught by Catch
without a second argument. If you seriously want to use exceptions in Mathematica, I would advice against such usage, since you can easily catch something you did not plan to catch - just as you wouldn't normally use Exception in Java, but would rather subclass it. There are no checked exceptions in Mathematica, so all Mathematica exceptions can be considered run-time exceptions. Since the second argument of Catch
is a pattern, you can construct Catch
commands that would be able to catch exceptions with different tags, somewhat emulating the exception inheritance hierarchies of Java. The syntax is also different - there is no try
- you just wrap Catch
around a piece of code from where you may expect an exception. Note that Catch with no second argument won't catch a tagged exception, while Catch
with the second argument won't catch an untagged exception. If you want both, you may need to nest like Catch[Catch[code,pattern]]. There is no finally
clause provided as a built-in, but one may emulate it with a user-defined code, since in Mathematica one can program the control flow constructs as well, using non-strandard evaluation (functions with Hold-attributes etc). You can look for use cases of Catch
and Throw
in the documentation, here on SO posts,and on MathGroup, and you will find plenty o good examples.
HTH
精彩评论