Home java Why do you need Throws in exceptions?

Why do you need Throws in exceptions?




Maybe I ask a stupid question, but I really do not understand why you need Throws if there is try and catch?
After all, Throws in essence does nothing he does not processes an exception and just throws them
So why then need Throws in exceptions?
Thanks in advance

Answer 1, Authority 100%

Exceptions are checked and unchecked (unchecked). The compiler requires all the exceptions that may arise in the program have been processed using Try-Catch (except for the exceptions specified in the Main method, see below). But it is not necessary to process the exception in the same method where it occurs (as in the Foo method). According to Throws, the compiler determines that the exception is not processed in this method, but is transmitted to the parent method (as in Oops ):

Public Static Void Main (String [] Args) {
 Try {
  oops ();
 } Catch (Exception E) {
  System.out.printLN ("OoSPS!");
 foo ();
Static Void Oops () Throws Exception {
 Throw New Exception ("Oops");
Static Void Foo () {
 Try {
  Throw New Exception ("Foo");
 } Catch (Exception E) {
  System.out.PrintLN ("Foooo!");

where in the chain of calls to handle this or that exception is determined from the reasons of the available context and architecture. An exception can not be processed if it is transmitted by challenges up to Main and indicated in its Throws:

Public Static Void Main (String [] Args) Throws Exception {
 bar ();
Static Void Bar () Thrown Exception {
 Throw New Exception ("Barrrr!");

Unchecked exceptions are inherited from RuntimeException. Among them, ArrayIndExOUTOFBOUNDSException, ArithMeticexception and others (see Direct Known SUBCLASSES) . An example of a code that always issues an exception, but compiled:

Public Static Void Main (String [] Args) {
 int a = getoutOfBoundSException ();
 int [] a = new int [] {1};
 Return A [2];

Unverified exceptions that occur in the method can also be listed after the word Throws , but they are doing it in rare cases when they clearly understand why. Usually it is not accepted.

Answer 2, Authority 100%

First, there are two keywords Throw and Throws . They are used in different ways and I will talk about them slightly below.

But first we will understand why you need mechanisms for processing exceptions at all.

There may be a reasonable question, “why not respond to an error right away how it originated?” Why do you need to “throw” an exception so that it is somewhere “catching” somewhere “and process?

The answer to this is this: not always part of the program in which the error happened, knows how to react to it.

For example, a network chat program (type Skype or Telegram) can use the Send system function, which actually sends a message over the network. How this feature works us as its users is not particularly interested in. Now imagine that during the message sending, the addressee computer turned off (roughly speaking electricity disappeared). The Send function will determine that it is impossible to send a message and here we have an error.

Now the question arises that with this mistake to do. The function itself does not know what to do with it. This feature was written by completely different people, they do not know which program they are going to use it. For example, a function cannot simply show an error message to the user, because it is possible that it is used in the program running on the server, where there is no screen, and the user may not be, since this is a server program that started scheduled, To download to the database, say, information about new currency courses from the Internet.

So, it turns out. that the function itself Send knows what a mistake happened, but does not know what to do with it. And who knows? And knows the client of this function, i.e. A program that caused the Send function. She knows exactly what to do. For example, a message “Could not send a message” and the button “Try again”, if it is a chat program. Or if it was a server program that downloads currencies to the database, it can send a letter to the administrator and schedule the re-execution of the download say in an hour.

So we approached Throw . This operator is just needed that Send can inform the calling error program, i.e. “Throw” (or otherwise “excite”) an exception to the Send type function (that is, the one that knows about the error, but does not know what to do if the error occurred).

Send will schematically look like this:

void send (String Data) {
 If (ConnectTotarget ()) {
   // here the implementation of the actual parcel over the network
 } else {
   Throw New CannotconnectException ("CANNOT Connect to Target Server");

Now, as for Throws . Question why this keyword needs to be quite difficult. Here I simplisticly describe in order to be clearer. In general, there are many nuances that I do not touch here (see numerous topics about Checked VS Unchecked Exceptions).

So, the keyword Throws is specified in the definition (signature) of the function and it suggests that the function can quit such an exception. For example, for Send will be like this:

void send (String Data) Throws cannotconnectexception {

At the same time, when you takua the function call, then either should this exclusion process, i.e. Wrap the send call to the try / catch block, or (if the calling function also does not know how to handle an exception) also declare in its signature that it can throw this exception .

Here is an important point that this need is to process or declare is monitored at the compilation stage, i.e. Before the program is running.

The idea of ​​the authors of the language was such that users of the functions, do not forget to process exceptions, and the compiler for this reminded and did not even allow compiling (and run) such a program.

Answer 3, Authority 50%

The same, why need specification of types. In order for the compiler to check the predictability of the program’s behavior.

Answer 4

These are the specifics of the language. To indicate that the method can cause an exception. For example, C # does not have this.

Do not look for meaning. It only gives you the visibility of the problem with this problem does not decide. This is how you marked the method problem, it will not be less problematic. The motto “warned means armed” – is actually only warned here, but to arm or not your task.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions