2010-04-07 68 views
2

try在java中做什么?在java中尝试做什么?

+14

有没有尝试只有做 – 2010-04-07 02:20:00

+1

以前没有问过这个问题吗?哦,不要忘了谷歌 – 2010-04-07 03:34:17

+0

嗯,做和(!做)。 – MJB 2010-04-08 20:47:53

回答

4

try/catch/finally结构允许你指定在情况下例外try块(catch)内发生运行代码,和/或代码,将try块后运行,即使一个异常已经发生(finally )。

try{ 
    // some code that could throw MyException; 
} 
catch (MyException e){ 
    // this will be called when MyException has occured 
} 
catch (Exception e){ 
    // this will be called if another exception has occured 
    // NOT for MyException, because that is already handled above 
} 
finally{ 
    // this will always be called, 
    // if there has been an exception or not 
    // if there was an exception, it is called after the catch block 
} 

无论发生什么,最终块对于释放资源(例如数据库连接或文件句柄)都很重要。如果没有它们,你将不会有一个可靠的方法在异常情况下执行清理代码(或者在try块中返回,中断,继续等等)。

+0

你能深入一点了解为什么Finaly块很重要吗? – David 2010-04-07 02:33:14

0

你们谈了 “的try/catch” 块。它用于捕获“try/catch”内代码块内可能发生的异常。异常将在“catch”语句中处理。

0

它允许您为一段代码定义一个异常处理程序。该代码将被执行,如果发生任何“异常”(空指针引用,I/O错误等),则会调用适当的处理程序(如果已定义)。

欲了解更多信息,请参阅维基百科上的Exception Handling

3

它可以让你尝试的操作,并在抛出异常的情况下,你可以处理它优雅而不是把它向上冒泡并暴露给用户一个丑陋的,而且往往无法恢复,错误:

try 
{ 
    int result = 10/0; 
} 
catch(ArithmeticException ae) 
{ 
    System.out.println("You can not divide by zero"); 
} 

// operation continues here without crashing 
1

try经常与catch一起用于运行时可能出错的代码,一个知道为的事件引发异常。它用于指示机器尝试运行代码,并捕获发生的任何异常。因此,例如,如果您要求打开一个不存在的文件,语言会警告您出现了问题(即通过了一些错误的输入),并允许您将帐户因为它通过将它包含在try..catch块中而发生。

File file = null; 

try { 
    // Attempt to create a file "foo" in the current directory. 
    file = File("foo"); 
    file.createNewFile(); 
} catch (IOException e) { 
    // Alert the user an error has occured but has been averted. 
    e.printStackTrace(); 
} 

可选finally子句可以一个try..catch块之后被用于确保一定的清理(如关闭文件)总是发生:

File file = null; 

try { 
    // Attempt to create a file "foo" in the current directory. 
    file = File("foo"); 
    file.createNewFile(); 
} catch (IOException e) { 
    // Alert the user an error has occured but has been averted. 
    e.printStackTrace(); 
} finally { 
    // Close the file object, so as to free system resourses. 
    file.close(); 
} 
+0

请注意,“catch”也是可选的。 – Thilo 2010-04-07 03:13:42

1

异常处理