简体   繁体   English

Java中的捕获与抛出异常

[英]Catching versus Throwing Exceptions in Java

So I have two general questions about java in general. 所以我一般有两个关于java的一般性问题。 The first is when would one use a try/catch in the body of the method versus using throws exception in declaring the method? 第一个是在方法体中何时使用try / catch而在声明方法时使用throws异常? Here is a little demonstration of what I mean. 这是我的意思的一点演示。 This: 这个:

public void whileChatting() throws IOException{}

versus

public void closeConnection() {
    try {
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
}

And then my second question is when does one know what type of exception to either catch or throw? 然后我的第二个问题是什么时候才能知道捕获或抛出什么类型的异常? By that I mean exceptions such as IOException or EOFException and so on... 我的意思是IOException或EOFException等异常......

If there's a good link someone could send me teaching all this (being that it's probably more complicated than I think) I would be just as grateful as if you answered it. 如果有一个很好的联系,有人可以让我教这一切(因为它可能比我想的更复杂)我会像你回答的那样感激。 Thanks. 谢谢。

Throwing Exceptions 抛出例外

In your first example, 在你的第一个例子中,

public void whileChatting() throws IOException{}

means that it will just throw the exception to whatever is calling the function. 意味着它只会将异常抛出到调用函数的任何东西。 It can then be caught while calling that method with a try-catch block. 然后可以在使用try-catch块调用该方法时捕获它。 such as

try{
    whileChatting();
}
catch(IOException e){
    e.printStackTrace();
}

Throwing a method basically propagates it up the chain, and so any method that calls this method will need to also include throws IOException , or the exception will need to be dealt with in the higher level method (by means of a try-catch block usually). 抛出一个方法基本上将它传播到链中,因此任何调用此方法的方法都需要包含throws IOException ,或者异常需要在更高级别的方法中处理(通常通过try-catch块处理) )。

Catching Exceptions 捕捉异常

Catching an exception is a way to gracefully deal with exceptions. 捕获异常是一种优雅处理异常的方法。 The common thing to do is e.printStackTrace(); 常见的事情是e.printStackTrace(); which prints details of the error to the console, however it's not always necessary. 它将错误的详细信息打印到控制台,但并不总是必要的。 Sometimes you may want to do a System.exit(0) or even a System.out.println("Error in method whileCalling()") 有时您可能想要执行System.exit(0)甚至System.out.println("Error in method whileCalling()")

With a catch block you can catch any type of exception! 使用catch块,您可以捕获任何类型的异常! you can also do a try-catch-finally block which will run the code in the try block, catch any exceptions, and whether or not any exceptions are caught it will enter the finally block and run that code. 你也可以做一个try-catch-finally块,它将运行try块中的代码,捕获任何异常,以及是否捕获了任何异常,它将进入finally块并运行该代码。

To know what Exception you might need to catch, you can look at the Javadocs for the class that may throw the exception. 要了解可能需要捕获的异常,可以查看可能引发异常的类的Javadoc。 There you will find a list of every possible thing that the class can throw. 在那里你会找到一个列表,列出班级可以抛出的每一件事。 You can also just catch Exception which will catch any Exception imaginable! 您还可以捕获Exception ,它将捕获任何可以想象的异常! (Well, granted it extends Exception) (好吧,授予它扩展Exception)

And finally you can link catch blocks together like so. 最后你可以将catch块链接在一起。

try{
    whileCalling();
}
catch(IOException e){
    //handle this situation
}
catch(FileNotFoundException e){
    //handle this situation
}
catch(Exception e){
    //handle this situation
}

This will work like and else-if block and not catch duplicates. 这将工作就像和其他 - 如果阻止而不是捕获重复。

So to answer your questions basically: 所以基本上回答你的问题:

1: To throw an Exception means to have somebody else deal with it, whether this be another class, another method, or just to hoping it doesn't happen or else your program will crash(pretty bad practice). 1: throw异常意味着让其他人处理它,无论这是另一个类,另一种方法,还是只是希望它不会发生,否则你的程序会崩溃(非常糟糕的做法)。

2: To use a try catch block is to actually deal with the Exception however you see fit! 2:使用try catch块实际上是处理Exception但是你觉得合适! printing out the stacktrace for debugging or giving the user a new prompt to re-input something maybe. 打印出堆栈跟踪以进行调试或为用户提供重新输入内容的新提示。 (For instance a prompt that the user needs to enter a file location and then it throws a FileNotFoundException ) (例如,提示用户需要输入文件位置然后抛出FileNotFoundException

Hope that helps! 希望有所帮助!

Two good rules of thumb: 两条好的经验法则:

There's no hard and fast answer. 没有硬性和快速的答案。

In general, you'll probably use "throws" much more often than you'll have a custom "try/catch". 一般来说,你可能会经常使用“抛出”而不是自定义“try / catch”。 Simply because you'll have relatively few "decision" modules that "know how to recover", but you'll have correspondingly "many" modules that could throw exceptions. 仅仅因为你将拥有“知道如何恢复”的相对较少的“决策”模块,但你会有相应的“很多”模块可能会抛出异常。

You use try/catch when you want to treat its reason, otherwise you should propagate it so it can be treated at the right time. 当你想要处理它的原因时你使用try / catch,否则你应该传播它,以便在适当的时候对它进行处理。

A good start would be javadoc and tutorialspoint for exceptions 一个好的开始是javadoctutorialspoint的例外

Basically is something like this: 基本上是这样的:

  1. throws - the function that throws and exception tells it's parent function that somenthing it's wrong. throws - 抛出的函数和异常告诉它的父函数,它是错误的。 For instance you have a createFunction() throws SQLException where you are trying to insert 100 item in a database but the creation of number 98 fails. 例如,你有一个createFunction()抛出SQLException ,你试图在数据库中插入100项,但创建数字98失败。 The createFunction() is used in your main() who receives this SQLException; createFunction()main()中用于接收此SQLException;

  2. try/catch - the main() knows that createFunction() is suppose to throw an SQLException if something goes wrong so when it implements it puts it in a try/catch block , this way if an SQLException is actually thrown you can execute a fall-back plan in the catch block such as a database rollback. try / catch - main()知道createFunction()假设在出现错误时抛出SQLException,所以当它实现时将它放在try / catch块中 ,这样如果实际抛出SQLException就可以执行fall catch块中的-back计划,例如数据库回滚。

    Actual code of what I just said: 我刚刚说的实际代码:

      createFunction(Connection connection) throws SQLException { //insert items in the database } main(){ try{ createFunction(connection); } catch (SQLException e){ connection.rollback(); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM