Is this syntax best method?
method 1:
input
method2():
method2: (input)
try
catch
return(method1())
method3: (input)
....
This is so when an exception is thrown you rarely want the program to crash, so it's best to have a return statement so the user can declare a new input for the variable. I am reading my textbook for class and they don't cover a return. Otherwise, without the return, having a try-catch seems pointless if the program just terminates.
Your syntax is simply vulnerable bacaues it can easily go stackoverflow by a malicious user's repeated inputs that cause the exception in method2.
How about this:
method 1:
while
input
try
return method2(input)
catch
method2: (input)
return (some result)
method3: (input)
....
If a piece of code is in an authorative position to know exactly what to do with an exception, it can catch it and do whatever that is.
If it's not, it should throw it up to allow a higher level piece of code handle it. Sometimes it necessary to wrap such an exception in order to keep things at the same level of abstraction as the method call.
At the top level, when there is an exception no code can handle, it's up to a person to deal with it. You log the exception and apologize to the user.
The exception can be caught in the calling code.
Say you're reading a file in a method
Data readFile(String filename) {
try {
// Open file here
} catch (Exception e) {
// something has happened but you caught it here itself.
// Caller of this method may not know that.
}
}
Instead if your method throws an exception (Predefined or your custom):
Data readFile(String filename) throws FileNotFoundException {
// Open file here. If file name wrong, it throws a FileNotFoundException
}
This time the calling code knows that the method may throw an exception and thus, handle it the way it wants.
for e.g.
Data data = null;
while(data == null) {
try {
String f = /*Some code to read a string from input*/;
data = readFile(f);
} catch(Exception e) {
System.out.println("Unable to read. " + e);
}
}
Ofcourse, there are other ways to do it.
Related
I am trying to handle an exception 2 times
The first is in the core of a defined method :
Class Class1 {
public int method (int a, String b) {
try {
System.out.println(a+" "+b.length());
}
catch (NullPointerException e) {
// TODO: handle exception
System.out.println("catch from the method");
}
finally {
System.out.println("finally from the method");
}
return 0;
}
}
and the second
is when I call this method in main and passing a null parameter to it :
public Class Class2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Class1 c = null;
try {
c = new Class1();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
c.method(1, null);
}
catch (Exception e) {
// TODO: handle exception
System.out.println("catch from the main");
}
finally {
System.out.println("finally from the main");
}
System.out.println("\nEnd of the main");
}
}
and the result is :
catch from the method
finally from the method
finally from the main
End of the main
And now my question is, why the catch block in the main was not executed?
Once you catch an Exception, it doesn't go any further, but you can throw it again. If you want your main to also see the exception you need to throw the exception again after it is caught. Try this:
public int method (int a, String b) throws NullPointerException{
try {
System.out.println(a+" "+b.length());
}
catch (NullPointerException e) {
// TODO: handle exception
System.out.println("catch from the method");
throw e;
}
finally {
System.out.println("finally from the method");
}
return 0;
}
Notice since there is a throw in the function now, you need to include it in the function definition
Edit: As stated by a couple of people, NullPointerException does not really need to be caught because it is an unchecked exception. This is because it is a subclass of RuntimeException.
You find many texts on the mechanics of throwing and catching exceptions. What I find more important is how to make best use of the exceptions concept.
This is not exactly an answer to your question, but maybe clarifies some concepts behind the situation at hand.
Rules of Thumb
If a method fulfilled its job, it should return normally. If it failed to do so, it should throw an exception instead of the normal return. The exception coming out of your method should contain information on the problem (most of the standard exceptions already do that quite well).
In a subordinate method, you normally shouldn't use try/catch. If something goes wrong (some exception arises inside your method), then your method typically can't complete its job, it should tell its caller by means of an exception, and the easiest way is to just let the exception ripple through.
In a top-level method (e.g. main, main-menu action, button-click action), catch all exceptions, inform the user (and maybe the administrator) and continue (if possible/appropriate).
If your method gets one exception (e.g. a NullPointerException) and wants to show a different one to its caller, catch the exception, create the desired new one, using the original one as cause, and throw this new exception. Personally, I try to avoid this "exceptions translation" as much as possible.
Use finally if you have to close some resource that you obtained inside the body, that would stay blocked for extended periods of time if not closed. Think of I/O streams, database connections/transactions and similar things. Don't do it just for memory allocation, that's the garbage collector's job.
If you follow these rules, you'll find that your code can concentrate on its main job, isn't cluttered with lots of error handling, and still is robust in case of exceptions.
Your Example
It all depends on the question "What's the job of Class1.method()?".
That might be "Print these two numbers". Then, when it gets the NullPointerException, it won't fulfill its job, so it shouldn't return normally, and instead exit with an exception, most easily by doing nothing (no try/catch at all) and just letting the exceptions framework do its automatic job. That will mean that its caller gets the original NullPointerException:
public int method (int a, String b) {
System.out.println(a+" "+b.length());
}
If the job of Class1.method() were "Print these two numbers, but only if there is a string", then you should catch the NullPointerException inside (or better, check with an if) and return normally ("I've done my job!"). Then Class2.main() should be satisfied with the non-printing in case of null, and have no reason to do any error handling after calling Class1.method(). If Class2.main() doesn't want that behaviour, it shouldn't call Class1.method() in that case.
This might be a weird question, but I still thought I would ask to get insights into this, and stop me from doing something wrong while I am coding.
Let's say I have a function func1(), inside which I call a function func2(). func2() throws an exception e1. And I want to catch this exception inside func1().
So does it matter whether I start a try block at the beginning of the function itself and end it at the end of func1() with the catch block, rather than just surrounding the part of the code where I call function func2().
I know from the coders perspective, where if an exception is thrown, he will be able to know exactly where the exception came from. If we ignore this, are there any other ill effects of just placing the whole method inside try-catch?
Edit - Code Fragment
So I am converting a JSON String to JSON Node. This operation throws an exception. But instead of surrounding this one statement with a try-catch block, I put the whole function inside the try block. It just looks cleaner to me. :)
public void storePublicData(String publicData, String twitterId) {
try {
Date date=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String day = formatter.format(date);
BasicDBObject query = new BasicDBObject("date", day);
query.append("brand_id", twitterId);
JsonNode publicDataJsonNode;
publicDataJsonNode = JSONOperations.castFromStringToJSONNode(publicData);
DBObject document = BasicDBObjectBuilder.start()
.add("brand_id", twitterId)
.add("date", day)
.add("followers", publicDataJsonNode.get("followersCount").asText())
.add("tweets", publicDataJsonNode.get("tweetsCount").asText())
.get();
twitterCollection.update(query,new BasicDBObject("$set", document), true, false);
} catch (JSONParamsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The biggest disadvantage is that you may also catch an exception you didn't intend to catch.
For instance, let's say you have a method that may throw a NullPointerException, and you can handle that case. (Such a method is probably badly written, but let's say it's a library method and you can't change it.) So, you catch the NPE:
void func1() {
try {
func2();
if (someString.equals("some value") {
someOtherFunction();
}
} catch (NullPointerException e) {
// handle func2()'s NPE somehow
}
}
There are two places a NPE could have been thrown within the try's body: from func2, or from someString.equals if someString is null. This code treats both the same way, which is probably a bug.
Generally speaking, in nearly all aspects of programming (variable scope, try-catch blocks, class members, etc), the smaller the scope is, the easier it is to reason about and the less likely you are to write bugs.
You can obviously use a try/catch block surrounding the entire body of the method, but confining it to the area that you are expecting an error adds readability to your code. I'm also fairly certain that they are very slow, and inefficient and there's no point to 'try' something where there's no possible IOException for example int i = 2 + 2;
I know from the coders perspective, where if an exception is thrown,
he will be able to know exactly where the exception came from
You nailed it right there: when you write a method you create a contract between you and the user. If you declare that the method throws an exception - it will be the responsibility of the user to catch and handle that exception. If it makes sense - you should do it (for example, throw an exception if you failed opening a connection to the DB). That said, in other cases, you might want to preform a fallback and just report to the user if the action was successful or not, in that case you can surround all the code inside method2 with try/catch and return a boolean value to save your users the extra coding of handling the exception.
well, if you have anything in funct1 after the call to funct2, that won't get executed if you place the whole method inside the try-catch.
im am citing Clean Code Book :
Error Handling Is One job, and functions should do one job.
Thus, a function that handles errors should do nothing else. This implies (as in the example above) that if the keyword try exists in a function, it should be the very first word in the function and that there
should be nothing after the catch/finally blocks.
so you should create a method that manages the exception , something like this:
public class Test {
public void doSomthing(){
// here i don't need to manage the exception because i have built parseDate(String date)
Date date = parseDate("10-17-2016");
}
private Date parseDate(String date){
Date result = null;
try {
result = new SimpleDateFormat().parse(date);//Throws Parse Exception
} catch (ParseException e) {
// Here you can:
//1) Throws other exception (Checked or Unchecked)
//2) Log the exception
// I think you should not re-throws the exception because
//is responsibility of this methods manage the exception
e.printStackTrace();
}
return result;
}
}
Basically iterating through a list and,
- Invoke method on first object
- Catch the first exception (if any); if there are no more exceptions to catch, return normally. Otherwise, keep on invoking method until all exceptions are caught.
- Move on to next object.
I can iterate through each object, invoke the method, and catch one exception but I do not know how to continuously invoke the method on it and keep on catching exceptions.
This is similar to the other answers, but without the flag, which seems like clutter to me. I don't really understand the question though, so I'm just throwing it out there in case it is useful.
for (Item item : items) {
while (true) {
try {
item.doSomething();
break;
} catch (MyException ex) {
log.warn("Something failed.", ex);
}
}
}
This approach hinges on the operation of the unlabeled break statement, which completes abruptly and then exits the enclosing while statement normally.
Based on subsequent comments, I think there is some confusion about what it means when there are multiple exceptions declared to be thrown by a method.
Each invocation of a method can be terminated by just one exception being thrown. You can't somehow resume invocation where it left off, and handle subsequent exceptions.
So, if a method throws multiple exceptions, catch a common ancestor, and move on. For example, if a method throws java.io.EOFException or java.nio.channels.ClosedChannelException, you could simply catch java.io.IOException since it is a common ancestor. (You could also catch java.lang.Exception or java.lang.Throwable for the same reason.) Invoking the method again under the same conditions won't get you any further.
If you want to attempt to invoke the method on each object, even if some fail, use this:
for (Item item : items) {
try {
item.doSomething();
} catch (Exception ex) { /* This could be any common ancestor. */
log.warn("Something failed.", ex);
}
}
If you're talking about dealing with a single method call that will throw more than one exception, it can't be done -- no matter how many times you call the method, it will keep on throwing the first exception. You can't go back into the method and keep running from there; after throwing one exception, it's all over.
But if you're talking about a method that sometimes throws exceptions and sometimes doesn't, try something like this:
boolean thrown = false;
do {
try {
thrown = false;
method();
}
catch (Exception e) {
thrown = true;
// Handle as you like
}
} (while thrown);
This is what I understand.
You have an object's method which may throw a number of exceptions.
What you want to do is to catch them all and continue with the next object in the list.
Is that correct?
So, that would be:
for( YourObject o : yourList ) {
try {
o.thatMethod();//invoke that risky method
} catch( SomeExceptionClass sec ) {
// Do something with that exception
} catch( SomeOtherExceptionClass soec ) {
// Do something with that exception
} catch( YetAnotherxceptionClass yaec ) {
// Do something with that exception
} catch( OtherUnRelatedException oue ) {
// Do something with that exception
}
}
When you do this, if the invocation of thatMethod() throws an exception and that exception is listed in the catch section, the execution flow will jump to that exception and after it will continue to the normal flow ( which is the for loop and will continue with the next object )
I hope this is what to need. For more information read: The catch block in the Java Tutorial section Essential classes
I'm assuming that you are trying to performs some kind of validation to the items in a list, where the validation errors are reported by throwing exceptions. I'm also assuming that you are trying to collect all of the validation errors.
The simple answer is that this problem cannot be solved using this approach. To understand why, take a look at this:
boolean exceptionCaught = false;
do {
try {
item.doSomething();
} catch (MyException e) {
exceptionCaught = true;
}
} while (exceptionCaught);
This fails because each time you call item.doSomething() it is going to throw an exception at exactly the same place. The net result is an infinite loop.
The best you can do with this approach is to capture the first exception for each item in the list.
So how can you achieve what you are trying to achieve? The answer is that you have to change the validation code to use some other way to report errors than throwing exceptions. For example, you could change:
class Item {
...
void validate() {
if (noHat) {
throw new MyException("bad hat");
}
if (noPants) {
throw new MyException("world-wide pants");
}
}
}
to something like this:
class Item {
...
void isValid(List<MyException> errors) {
boolean ok = true;
if (noHat) {
errors.add(new MyException("bad hat"));
ok = false;
}
if (noPants) {
errors.add(new MyException("world-wide pants"));
ok = false;
}
return ok;
}
}
Messy huh! You could sugar this in various ways, but this style of error reporting is always going to be more complicated. But I don't think there is a practical way to avoid the messiness AND capture ALL of the validation errors.
( patience requested as i'm new to programming )
when you add the phrase throws ABCexception in method declaration like this
public static void main(String[] args) throws ABCException {
}
does it mean that the you expect the method could generate an ABC exception and by writing throws ABCException ... when this exception occurs .. this exception will be caught and some prewritten code in java language will be executed corresponding to the ABCException. ?
thanks
throws declares that the method may throw the exception so the code that invoke this method must be prepare for it.
Being prepared for exception means that the code may catch the exception or re-throw it up.
Consider the constructor new FileInputStream(File pFile) which will create a FileInputStream from a File object. Since the file may not exist or not readable the constructor will throw FileNotFoundException (as declared).
So any code that call this constructor will either catch or rethrow it.
Catching it, the code will taking care of that exception by themself while rethrowing it, the code will let its caller take care of it.
Consider the following two codes:
Code 1: Catch -> Take care of it
public String readTextFile(File pFile) {
try {
FileInputStream FIO = new FileInputStream(pFile);
... // Do the reading and return
} catch (FileNotFoundException E) {
System.err.println("The file is not found");
}
}
Code 2: Throw -> Let the caller take care of ot
public String readTextFile(File pFile) throws FileNotFoundException {
FileInputStream FIO = new FileInputStream(pFile);
... // Do the reading and return
}
So the caller of readTextFile will have to catch or rethrow it too.
This mechanism ensures that someone have to take care of the exception in someway.
I hope I help.
The thows ABCException statement, before the function definition starts in earnest is just to indicate that this function may throw such an exception.
The actual throwing of the exception would happen within the code of the function. With code like the following (note the lack of an 's' at the end of "throw")
throw new ABCException();
The exceptions are then passed on "up" through the chain of the program logic that called this function this function, until one these "catches" the exception and deals with it. In case the exception "bubbles back" all the to the main() function, and if said exception isn't caught there either, a default handler deals with it, typically by printing out the exception to stderr/stdout and halting.
The way this exception could be caught would be with a try-catch construct, as in:
try
{
// do some stuff if needed
xy = fct(); // this fct may throw the ABCExeption...
// do more stuff as well
}
catch (ABCException e)
{
// for debugging you can do this
e.printStackTrace();
// otherwise you could deal with this exception as desired.
}
In re-reading the question, I noted that the function which is declared with throws ABCException and that is a bit odd, because main is the first method in the chain of function calls, meaning that there is nothing before main() which could catch an exception (other than the default exception handler of the Java Runtime, which wouldn't do anything specific for ABCException; it would just "dump it" to the console (or elsewhere for GUI-based apps) like any other exception.
I am getting an error in NetBeans saying I must throw an SQLException in this method:
private void displayCustomerInfo(java.awt.event.ActionEvent evt)
{
int custID = Integer.parseInt(customerID.getText());
String info = getCustomerInfo(custID);
results.setText(info);
}
This method is created by NetBeans so it is not allowing me to edit the signature and throw the exception. This is why I created the getCustomerInfo() method. This method does throw the exception, because it uses a method to retrieve information from a database about a customer.
public String getCustomerInfo(int cid) throws SQLException
{
Customer c = proc.getCustomer(cid);
// get info
return "info";
}
The getCustomer method also throws the exception and proc.java compiles.
The exact error is
unreported exception java.sql.SQLException; must be caught or declared to be thrown
In general, if your code needs to throw a type of Exception that the signature doesn't support, and you have no control over the interface, you can catch and rethrow as a type the interface does support. If your interface doesn't declare ANY checked exceptions, you can always throw a RuntimeException:
private void displayCustomerInfo(java.awt.event.ActionEven evt)
{
try
{
int custID = Integer.parseInt(customerID.getText());
String info = getCustomerInfo(custID);
results.setText(info);
}
catch (SQLException ex)
{
throw new RuntimeException(ex); // maybe create a new exception type?
}
}
You almost definitely want to create a new Exception type that extends RuntimeException, and have your client code catch that exception. Otherwise, you run the risk of catching ANY RuntimeException, including NullPointerException, ArrayIndexOutOfBoundsException, etc., which your client code probably can't handle.
Read the error message again, it gives you two choices.
You must either declare the exception as thrown (which you cannot do) or catch the exception. Try the 2nd choice.
You need to put a try/catch block around your call to getCustomerInfo(), like so:
private void displayCustomerInfo(java.awt.event.ActionEvent evt)
{
int custID = Integer.parseInt(customerID.getText());
try {
String info = getCustomerInfo(custID);
} catch (SQLException sqle) {
// Do something with the exception
}
results.setText(info);
}
A couple good options for handling the exception might be: logging the exception and the details used to get it, or using it as a signal to retry the connection request. Alternatively, as Outlaw Programmer shows, you could re-throw the Exception as a RuntimeException of some kind, which removes the requirement of checking.
It does not say you must throw it. It says you can catch it. So use a try/catch block and handle it.
try {
...
}
catch (SQLException e) {
System.out.println("Exception happened! Abort! Abort!");
e.printMessage(); //Not sure if this is the correct method name
}
NetBeans generated components have un-modifiable code, and I'm guessing that it is generated as a part of the gui builder. I'd ask if this was the case, but I can't comment yet. If you select a generated object in the GUI editor, on the right there is a tab "code" that can be used to modify the grayed out area of the code.
Here:
I've come across this problem... been puzzled for the past 2 days.. then I open the source (.java file) with sublime, change the code, save, and it works wonders... I'm laughing when I see this works... think outside the box really works...