大家好.我一直在阅读Apple关于何时/何地/如何使用NSError与@ try/@ catch/@的建议.从本质上讲,我的印象是Apple认为最好避免使用异常处理语言结构,除非作为在意外错误情况下暂停程序执行的机制(也许有人可以举例说明这种情况?)
我来自Java,当有人想要处理错误时,会有例外.不可否认,我仍然在Java思想空间,但我正在慢慢掌握NSError所提供的所有内容.
我挂断的一件事是在发生错误时清理内存的任务.在许多情况下(例如使用C,C++库,CoreFoundation等),您需要在由于错误而导致函数中断之前进行大量内存清理.
这是我煮熟的一个例子,它准确地反映了我遇到过的情况.使用一些虚构的数据结构,该函数打开一个文件句柄并创建一个"MyFileRefInfo"对象,其中包含有关如何处理该文件的信息.在关闭文件句柄并释放struct的内存之前,对文件执行了一些操作.使用Apple的建议我有这个方法:
- (BOOL)doSomeThingsWithFile:(NSURL *)filePath error:(NSError **)error
{
MyFileReference inFile; // Lets say this is a CF struct that opens a file reference
MyFileRefInfo *fileInfo = new MyFileRefInfo(...some init parameters...);
OSStatus err = OpenFileReference((CFURLRef)filePath ,&inFile);
if(err != NoErr)
{
*error = [NSError errorWithDomain:@"myDomain" code:99 userInfo:nil];
delete fileInfo;
return NO;
}
err = DoSomeStuffWithTheFileAndInfo(inFile,fileInfo);
if(err != NoErr)
{
*error = [NSError errorWithDomain:@"myDomain" code:100 userInfo:nil];
CloseFileHandle(inFile); // if we don't do this bad things happen
delete fileInfo;
return …Run Code Online (Sandbox Code Playgroud) error-handling cocoa memory-management objective-c try-catch-finally
public Foo doDangerousStuff() throws Exception {
try {
dangerousMethod();
return new Foo();
} catch (Exception e) {
throw e;
} finally {
mustBeCalledAfterDangerousMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
这与我们省略catch子句的行为有什么不同吗?
public Foo doDangerousStuff() throws Exception {
try {
dangerousMethod();
return new Foo();
} finally {
mustBeCalledAfterDangerousMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
[编辑]为了清除混淆,是的,catch除了重新抛出异常之外,该块不执行任何操作.我想知道这是否会在finally调用块时引起某种不同的排序(假设调用者捕获了抛出的异常),但是从我从答案推断出来的情况来看,它并没有.
internal static string ReadCSVFile(string filePath)
{
try
{
...
...
}
catch(FileNotFoundException ex)
{
throw ex;
}
catch(Exception ex)
{
throw ex;
}
finally
{
...
}
}
//Reading File Contents
public void ReadFile()
{
try
{
...
ReadCSVFile(filePath);
...
}
catch(FileNotFoundException ex)
{
...
}
catch(Exception ex)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码示例中,我有两个函数ReadFile和ReadCSVFile.
在ReadCSVFile中,我得到FileNotFoundExexoon类型的异常,它被catch(FileNotFoundException)块捕获.但是当我抛出此异常以捕获ReadFile()函数的catch(FileNotFoundException)时,它会捕获catch(Exception)块而不是catch(FileNotFoundException).而且,在调试时,ex的值表示为Object Not Initialized.如何将调用函数的异常抛出到调用函数的catch块而不丢失内部异常或至少发出异常消息?
public class J {
public Integer method(Integer x)
{
Integer val = x;
try
{
return val;
}
finally
{
val = x + x;
}
}
public static void main(String[] args)
{
J littleFuzzy = new J();
System.out.println(littleFuzzy.method(new Integer(10)));
}
}
Run Code Online (Sandbox Code Playgroud)
它将返回"10".
现在我只是将Return type Integer替换为StringBuilder并更改了Output.
public class I {
public StringBuilder method(StringBuilder x)
{
StringBuilder val = x;
try
{
return val;
}
finally
{
val = x.append("aaa");
}
}
public static void main(String[] args)
{
I littleFuzzy = …Run Code Online (Sandbox Code Playgroud) 我在MDN上读到了try catch(e,如果是instanceof ...)块,但是,在Node.js中尝试它时,我得到一个SyntaxError:Unexpected token if.
如果这不起作用,是否有另一种方法来捕获特定的异常,而不是可能发生的一切?
我有以下代码段/示例.它不是工作代码我只是写了这个,以便问一个关于catch的问题,最后并返回:
try
{
doSomething();
}
catch (Exception e)
{
log(e);
return Content("There was an exception");
}
finally
{
Stopwatch.Stop();
}
if (vm.Detail.Any())
{
return PartialView("QuestionDetails", vm);
}
else
{
return Content("No records found");
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,如果try块中有异常,它将会捕获.但是如果catch中有return语句,那么最后会执行吗?这是编码捕获的最终方法吗?
在finally子句中编写try和catch是否被认为是错误的编程?
我在我的main方法中有一个我要关闭的fileInputStream.我想将.close()放在finally中,所以它无论如何都会关闭.我不想在main方法中添加throws声明,因为它是主要方法:P
}finally{
try {
commandFile.close();
} catch (IOException e) {
throwException(e);
}
}
Run Code Online (Sandbox Code Playgroud)
好吗?谢谢
"finally"和"catch"之后写的有什么区别?
例如:
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
} finally {
return true;
}
}
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
}
return true;
}
Run Code Online (Sandbox Code Playgroud) 我很困惑为什么我需要将清理代码放在一个finally块中关闭流.
我已经读过finally块中的代码无论如何都会运行(是否存在异常); 并且在finally块运行之后,该方法的其余部分继续.
我的问题是:如果方法的其余部分必须继续,那么为什么我不在函数中的try/catch块之后放入清理代码?
我有以下代码.
public static void main(String[] args) {
System.out.println(returnString());
}
private static String returnString(){
try {
System.out.println("Executing try");
return "Return try value";
} catch (Exception e){
System.out.println("Executing Catch");
return "Return catch value";
} finally {
System.out.println("Executing finally");
return "Return finally value";
}
}
Run Code Online (Sandbox Code Playgroud)
这个输出是
Executing try
Executing finally
Return finally value
Run Code Online (Sandbox Code Playgroud)
如果我改变我的finally块而不返回任何类似的东西
public static void main(String[] args) {
System.out.println(returnString());
}
private static String returnString(){
try {
System.out.println("Executing try");
return "Return try value";
} catch (Exception e){
System.out.println("Executing Catch");
return "Return catch …Run Code Online (Sandbox Code Playgroud) java ×6
c# ×2
try-catch ×2
cocoa ×1
control-flow ×1
exception ×1
javascript ×1
node.js ×1
objective-c ×1
return ×1
return-value ×1