Java: try block and catch block

Status
Not open for further replies.
Also, the java compiler will force you catch exceptions, like NumberFormatException, etc.

Besides, even though it is not that efficient, exceptions is a clear way of returning errors. For example, if I have a function:
double getFrac(int numerator, int denominator), what should happen if the denominator is zero? Should we return -1?, Then what happens if I do getFrac(1,-1)? As its name implies exceptions are used for telling the caller that something out of the ordinary had just happened and the function is confused on what to do.
 

pyu

Ars Praefectus
5,108
Subscriptor
the try=catch block enables you to catch exceptions and do some processing so that your program is able to ask for new input and correct itself - if it is possible in the first place -- so that it is possible to continue on.

the other kind I can think of --> nameofmethod(int i) throws typeOfException -- doesn't do that. The compiler catches that error and stops the program.
 

MilleniX

Ars Tribunus Angusticlavius
8,139
Subscriptor++
Originally posted by pyu:
he other kind I can think of --> nameofmethod(int i) throws typeOfException -- doesn't do that. The compiler catches that error and stops the program.
That's not true. When calling a function that explicitly throws
Code:
TypeOfException
, the function call should be within a
Code:
try {...}
block, and there should be a matching
Code:
catch (TypeOfException myException) {...}
block.

MilleniX
 
How does one solve this try/catch problem?

Imagine method wham() returns an int, and throws an exception if something goes wrong.

So I can't do
Code:
int x = wham();

I have to do
Code:
int x;
try
{
  x = wham();
}
catch(Exception e)
{
 //do something with e
}

The problem is, if I try to use x for something outside of the try block, the compiler complains that it might not be initialized yet. This can get annoying...what's the proper way to deal with it?
 
Status
Not open for further replies.