Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why try...catch requires EXACT type thrown

I can do this, no problem:

long lngval = 3L;
int i = lngval;

but if I try this:

try {
  throw 3L;
}

catch(int i) {
  cout << "caught " << i << endl;
}

I get an unhandled exception.

This seems inconsistent. what is the reason for no type conversion in this case?

like image 208
Angus Comber Avatar asked Sep 27 '11 14:09

Angus Comber


People also ask

Does a try catch need a throw?

When your code throws a checked exception, you must either use a try block to catch it, or use the throws keyword on your method to advertise the fact that it throws an exception to any method that may call it, so that it in turn must either use a try block to catch it or use the throws keyword to pass the buck.

Why to use throws keyword if we have try catch block?

throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

What is the use of try catch throw in exception handling?

Java try and catch The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

What is difference between try catch and throws?

The try statement defines a code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.


1 Answers

In the first case, the compiler can tell exactly what you want to do: convert a long to an int. In the second case, the compiler has to assume that you might have a construct like this:

try {
  try {
    throw 3L;
  }
  catch (int i) { /* P */ }
}
catch (long l) { /* Q */ }

The idea is that the compiler can never know whether there might be a catch (long l) lurking outside the current context, so it's never safe to just pick the first possible conversion.

This is also why it's common to use a class hierarchy when throwing exceptions rather than random types like int or long: it makes it easy to add more or less specification to your exception handlers in such a way that the compiler can be sure of your intentions (via the is-a relationship).

like image 137
ladenedge Avatar answered Oct 03 '22 16:10

ladenedge