尝试在java中做什么?

时间:2010-04-07 02:08:24

标签: java exception-handling try-catch

try在java中做了什么?

7 个答案:

答案 0 :(得分:7)

答案 1 :(得分: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块返回,中断,继续等等)。

答案 2 :(得分:3)

它允许您尝试操作,并且在抛出异常的情况下,您可以优雅地处理它,而不是冒泡并以丑陋且通常无法恢复的错误暴露给用户:

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

// operation continues here without crashing

答案 3 :(得分: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();
}

答案 4 :(得分:1)

异常处理

答案 5 :(得分:0)

你在谈论一个“尝试/捕获”块。它用于捕获“try / catch”中代码块内可能发生的异常。例外情况将在“catch”声明中处理。

答案 6 :(得分:0)

它允许您为代码块定义异常处理程序。此代码将被执行,如果发生任何“异常”(空指针引用,I / O错误等),将调用相应的处理程序(如果已定义)。

有关详细信息,请参阅维基百科上的Exception Handling