开发者

Why do you have to write throws exception in a class definition?

开发者 https://www.devze.com 2022-12-15 07:44 出处:网络
Com开发者_如何学Cing from C#, I just don\'t get this \'throws exception\' that is written after a class/method definition:

Com开发者_如何学Cing from C#, I just don't get this 'throws exception' that is written after a class/method definition:

public void Test() throws Exception

Do you have to write this? What if you don't? If I call a method that has this symbol, do I have to catch it?


You don't have to write it in all cases -- you just have to write it if your method throws a checked Exception (an exception that is a subclass of Exception and not a subclass of RuntimeException). This is because your method signature is a contract, and it's declaring to all the code which calls it that it has the potential for throwing the given exception. Because it's a checked exception -- an exception which can be anticipated -- the calling code needs to anticipate the potential of seeing the exception thrown, and needs to be able to handle it.

To answer your two specific questions:

  • do you have to write it/what if you don't: if your method throws a checked exception, then yes, you have to declare it in your method signature. If you don't, then your code won't compile.
  • do you have to catch it: you have to do something with it. The code calling the method can either catch it and handle it, it can catch it and re-throw it, or it can just pass it up the chain. In order to pass it up the chain, the code calling the method has to itself declare that it throws the same exception -- e.g., if method bar can throw SomeException, and method foo calls bar and doesn't want to catch the exception, the method signature for foo would declare that it too throws SomeException.

The Exceptions chapter of the Java lessons is very good at explaining this in detail, and JavaWorld has a good article about throwing and catching exceptions that I've always found to be a good reference to pass onto folks.


Basically yes, and if you don't your program won't compile. This is called a checked exception (Any exception is a checked exception unless it is or extends RuntimeException or Error).

If there is anything in the method which throws an Exception it won't compile unless you either catch the exception or declare it on the method, and then anything calling that method will have to handle the Exception in the same manner.


To answer your specific question, you almost never want to say throws Exception per se.

The throws clause is notifying users of this method that there is an exceptional case that they will have to handle. For example, you might have an IOException that results from some use of the file manipulating methods (e.g., unable to open the file in question). If you haven't handled that locally, you need to declare that your method throws that exception back to the caller.

Modern IDEs will notify you that, for checked exceptions, you need to either handle them in your use of the method or throw them out of the method up the call tree (via the throws clause).


You have to write it in the case that the exceptions thrown are checked exceptions, which mean that it is the explicit responsibility of the caller to catch or rethrow the exception.


You don't have to throw the exception if you catch the exception in your code. If you don't catch it, it gets passed along to the caller, which is why you would need the throws clause.


This concept of checked vs. unchecked exceptions doesn't exist in .net. The intention of the original Java guru's was that if you have to declare the checked exceptions that you throw, so the caller will know that he/she has to catch them. for example, if you are dealing with the IO library, if forces you to catch the IOException.

try {
    file.delete();
} catch (IOException x) {
    // do something
}

Unfortunately checked exceptions are over-used in Java (see spring philosophy). There is a lot of criticism about the abuse of checked exception and how they pollute the code. Libraries that throw checked exceptions more often than not lead the users to write code like this:

try {
    file.delete();
} catch (IOException e) {
   throw new RuntimeException(e);
}

If you are writing a library, consider whether your checked exception will hinder/annoy the user, and whether he/she benefits from having to catch them.

There are different school of thoughts on this matter, but the overwhelming trend today is to avoid checked exceptions (see successful projects like spring, hibernate, apache-commons, etc.).

I can attest that today I don't throw checked exceptions anymore. If it is really important that the user should know about the exception, then document it well in the javadocs, but give the user the freedom to write cleaner code.

EDIT: I found a similar question (and one of my previous answers) here. Maybe it will help.


In C++ ( I can't C# but it is probably similar ) keyword throw is a restriction for all of exception types so if there is no specification about throwing exceptions you can suppose that it can be whatever.

In Java you can suppose if there is no usage of keyword throws then this method throws no one. ( you can be sure, but there needn't be runtime exceptions ). So if there is some specification about throwing you have to catch it of propagate it up


"throws" keyword is used if the exception may not gonna handle in current method and it can be propagated to the caller of that method.

The caller can either handle that exception or propagate that exception to another method by using "throws" keyword.

The Exception class is base class for Runtime Exception.


Answer more to the topic rather to description: Class can not use "throws" keyword. Only methods and constructors can.

With little hack you can use throws on initialization block (but not static). You can set throws on constructor and then it will compile.

public class Example{ // here you can not use throws
{
    BufferedReader in = new BufferedReader(new FileReader("asdf"));   
}   
public AbstractWithConstantsOnly() throws FileNotFoundException {   }

public static void main(String[] args) throws Exception {
    new Example();
}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消