Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

java - When to throw specific exception and when to output error to console using system.out

I was designing an oop model where I got confused between throwing exception and outputting it through system.out using if else I was doing like

public void fun(int n) {
if(n<0){
    System.out.println("n less than 0");
}
}

I could have also done like

public void fun(int n) throws InvalidNumberException{
if(n<0){
    InvalidNumberException("n less than 0");
}
}

Which is the good way to actually do that. Should I throw exception and catch it or just use if else to output.

question from:https://stackoverflow.com/questions/65859058/when-to-throw-specific-exception-and-when-to-output-error-to-console-using-syste

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Throwing an exception is meant to be handled by the caller. Make a custom checked exception for the situation you are in and wrap important information in that checked exception so that the caller can handle it.

If the user is supposed to input something more appropriate and can respond to the system, then print out the error and give the user the ability to correct his input data.

If the system can continue to work correctly; however you wish to track some errors that might be unforeseen, you may log the error to correct the error in future releases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...