Answer the question
In order to leave comments, you need to log in
What expressions to use?
Hi) What train of thought / algorithm should be when choosing Exception'a?
For example, I wrote a class:
import java.util.Scanner;
public class Scan {
private Scanner scanner = new Scanner(System.in);
public int scanInt() {
try{
return scanner.nextInt();
}
catch (Exception exc){
return 0;
}
}
}
Answer the question
In order to leave comments, you need to log in
If the class does not do anything critical in the program, then it is possible and necessary to handle all exceptions within this class. If the class performs some critical actions, then most likely it can be very dangerous to handle exceptions within the class and it is better to catch them at a higher level.
Not a critical example: the class draws a picture on the screen, if a couple of pixels are somehow null during processing and you catch this exception by replacing the erroneous pixel with white, then nothing criminal will happen. But if you catch an exception a level higher, then there will be a lot of unnecessary crap and code.
A critical example: a class works with a database that stores data about people, an error occurs, say, with access to the database, you caught exceptions within the class itself and instead of returning, for example, "Ivanova A.P.", you have an exception, and instead of throwing an exception up, you pretend to be a hose and return that there are none. The code is somewhere further, seeing that everything is fine and "Ivanova A.P." is not present in basis quietly creates there new (connection with a DB could be restored by this moment) instead of updating record. Those. in such a situation, it is simply wrong to handle exceptions inside the class in most cases. iron concrete it must be processed higher and in case of an error in accessing the database, fall off and try everything again.
Should I use Error-handling inside the method, or use throws and catch it in main() ?
nextInt
the one that throws a checked (checked) exception is an obvious excess that greatly complicates the code, so do the processing inside your Util-method, in case of an exception, return null
, you can develop and apply your own logging mechanism, which is more flexible and convenient.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question