Try Catch in main or in method - java

So I am task with getting input for clock time. With 3 method
gethour , getmin , getsec inside the method we are suppose to check if the value is between 0 and 60 if its not throw exception.
My question is :
Is it better to do try catch inside my main or should i do it inside the method?
I did it in method cause i felt that it was better(just my thought) and my prof deducted marks from it stating its better to do it in main. So i just want to know which is actually better and why.

Whenever you're catching exceptions you should catch at whichever level is the most reasonable to handle that error.
If you can't handle it, you should let it propagate up the stack. If you can handle it in a reasonable way then you should catch it and take the appropriate action to correct the failure.
That's really all there is to it. Whenever you write a catch statement you should be asking yourself "is there actually anything I can do to fix this at this point in the code?"
For example, if you expect to find a configuration file and it's missing then maybe the appropriate action is to fall back to some sensible default configuration values.
Without your code or any context of what the error is, or what levels of your call stack are doing what, we can't tell you any more than that.

If your method should throw exception by definition than it doesn't need to catch any exception, because it should be defined as throwing the exception and actually throwing an exception

The practice in exception handling is that you should be catching exceptions closets to where they occur. It makes it easier to trace back, while also makes better flow control. Try-catch is mainly used to prevent your program from crashing upon very unusual circumstances, while displaying user-friendly error message to user and logging the complete error somewhere else.
However, if you are already handling the exceptions correctly, in a task-specific way, then a more general try-catch method can be used as a failsafe for bugs in edge cases that didn't get caught during testing, or for very rare occurences.

A good practice is to handle exceptions only when you can take some meaningful action on it. I don't have your full example, but I suppose that if you catch the exception inside the method, you would need to return some value to the caller. And then how would the caller know if you had invalid data (outside of 0..60 range) in your method?
On the other hand if you throw an exception and handle it in the main(), you would have more options to do that and the method would not hide the error situation.
This is also called separation of concerns. Method functionality and error handling are separate concerns and they should not be mixed. If you handle the exception in main(), you'll have a better SoC: functionality in the method, error handling in main()

Actually it doesn’t matter where to put the try-catch block. If you don’t want to catch the exception inside your method and throwing back to caller method i.e main() , then you can handle it there. It purely depends on the requirements. I am not sure why your professor did this. You can ask him.

Related

What's the point of try/catch blocks to catch Exceptions?

Why do we need try/catch blocks to catch any Exceptions that may arise in our code? Once we run the program and lets assume we have a RuntimeException, won't the program just automatically abort and give us the error anyways? Why do we need try/catch blocks to do this for us then?
It's just good practice. If the user is given with something like "IndexOutOfrangeexception" what is he going to do with it? Just assume everything is OK and he should start over? What in case of doing some work with the software - is the work lost? What happened?
Put yourself in such stuation: you downloaded some software, you start using it as normal, and you are happy with it. But one day you run program and it gives you error and program dies - do you know what happened? No. Do you know what went wrong? No. Do you know how to prevent it and start using software so the error doesn't occur again? No.
YOU ARE THE DEVELOPER, you know what happens inside. So for example, you are trying to save data in database, but somehow connection got lost and you will likely get an exception - in catch block you can catch this exception and give the user MEANINGFUL information, e.g. "The connection with database is lost. Check the network. Your data is not saved and you should do the work again." - isn't that better than just some "SQL exception" alongside with the stacktrace?
Additionally, catch/finally blocks are here to clean-up potential mess, for example you are writing some content to a file, but it only makes sense, when you can write all data, not just the part of it. So in catch block you could erase incomplete data, so the file is not corrupted for example.
Also, when working with unanaged resources, you should use finally block to clean them up (for example DB/netowrk connections).
Think about the scenarios when working with a live website or application. You wouldn't want the user to see a blank screen or a screen full of error trace code. In such scenarios, potential areas of exception can be handled to show a message to the user that makes sense "sorry, you are exceeding more than 10 items in your cart etc ", "you do not have sufficient amount in your account", "username cannot have symbols ", "out service us un-operational right now please come back later".
Try catch is used to handle the such error conditions gracefully. You can enclose a code set into try and its catch would be responsible to handle it. Handling may depend on your use case but your java program wont terminate.
Abrupt termination of program doesn't let you know the actual reason of failure.
Because if you don't catch an exception the entire method execution will simply stop, including the execution of any calling methods. So if a method A needs something of method B and calls it, and method B throws an exception, then that exception will cause method A to stop execution. If method A was being called by another method that method will stop execution too if it doesn't catch the exception from method B. So an exception will work its way up the method calling chain until it is catched by a method or gets to the most upper/outer method.
Also, any exception that is not inheriting from the RuntimeException class or is not an instance of the RuntimeException class itself must either be catched or else your code will not compile. If you really don't want to handle this kind of exception then you can also let the calling method receive the exception by adding throws Exception to your method signature. A runtimeexception extending class is called an unchecked exception, you don't have to include that in the method or in the method signature. Anything extending Exception but not RuntimeException is called a checked exception and should either be catched or put in the method signature by using throws keyword.
EDIT: Here you can find a good explanation too Does every exception have an required try-catch?
Other than examples users given, also, on Android for hardware specific operations, camera for instance, can throw RuntimeExceptions even you do everything right, it does it a lot with camera based on devices. I set ISO for instance camera and it's not a crucial for my app to work but i don't want my app to crash so i throw an exception and show a warning to user so app continue to work.

Is it a good practice to use nested exceptions?

This is probably a broad question, not quite SO style, but I'd still like to get some hints or guidelines if possible.
I've been looking through some legacy code and found a part of it that has methods with exceptions nested 3 or 4 levels down.
Is this considered to be a normal practice or should one avoid such codestyle where possible? If it should be avoided, what are the negative effects besides the increasing costs of exception handling and decreasing readability? Are there common ways of refactoring the code to avoid this?
I personally prefer the following ideology
Wrap Alien Exceptions
An "alien" exception is an exception thrown by a Java API or a third party library. In other words, an exception you do not control.
Its better to catch all alien exceptions and wrap them in an appropriate application specific exception. Once the alien exception is converted to your own exception, you can propagate that exception any way you like.
Rethrowing Checked Exceptions can get Messy
If your application uses checked exceptions, rethrowing the original exception means that the method rethrowing it must also declare it.
The closer you get to the top of the call hierarchy, the more exceptions will be declared thrown. Unless you just declare all your methods to throw Exception. However, if you do so you might as well use unchecked exceptions, since you are not really getting any benefit from the compiler exception checking anyways.
This is why I prefer to catch non-application specific exceptions and wrap them in an application specific exception, before propagating them up the call stack.
Guidelines For Wrapping : The context in which an exception occurs may be just as important as the location of the exception itself. A given location in the application may be reachable via different execution paths, and the execution path may influence the severity and cause of the error, if it occurs.
If you need to add context information to an exception as you propagate it up the call stack, you need to use active propagation. In other words, you need to catch the exception in various relevant locations on the way up the call stack, and add the relevant context information to it, before rethrowing or wrapping it.
public void doSomething() throws SomeException{
try{
doSomethingThatCanThrowException();
} catch (SomeException e){
e.addContextInformation(“more info”);
throw e; //throw e, or wrap it – see next line.
//throw new WrappingException(e, “more information”);
} finally {
//clean up – close open resources etc.
}
}
Checked Exceptions should not be propagated up the stack or chained if possible. If a method is throwing a checked Exception its caller is supposed to handle it, if caller is not handling it and propagating it to its caller, then overall complexity increases.
In a three layered example : Dao , Service , Controller
DAO layer will throw DAOException
Service layer should not expose DAOException to Controller , instead it should be throwing relevant BuinessExceptions, which the Controller should be handling.
Exception handling tends to be an expensive way to handle flow control (certainly for C# and Java).
The runtime does quite a lot of work when an exception object is constructed - getting the stack trace together, figuring out where the exception is handled and more.
All this costs in memory and CPU resources that do not need to be expanded if flow control statements are used for flow control.
Additionally, there is a semantic issue. Exceptions are for exceptional situations, not for normal flow control. One should use exception handling for handling unanticipated/exceptional situations, not as normal program flow, because otherwise, an uncaught exception will tell you much less.
Apart from these two, there is the matter of others reading the code. Using exceptions in such a manner is not something most programmers will expect, so readability and how understandable your code is suffer. When one sees "Exception", one thinks - something bad happened, something that is not supposed to happen normally. So, using exceptions in this manner is just plain confusing.
Please take a look at below links
Exception Handling: Common Problems and Best Practice with Java 1.4 - pdf
Why not use exceptions as regular flow of control?
Best Practices for Exception Handling
Error Handling
Mr. Google Links
I've been looking through some legacy code and found a part of it that has methods with exceptions nested 3 or 4 levels down.
Is this considered to be a normal practice or should one avoid such codestyle where possible?
This is not a necessary process to handle your exception in this way, as it will increase your application overhead, until you really need to handle very specific exception(checked or Alien Exceptions) and you can ignore overhead to get specific information to handle that exception.
If it should be avoided, what are the negative effects besides the increasing costs of exception handling and decreasing readability?
As I mentioned you will not get specific information about the exception, if you are not going to use nested exception handling(throws with some added information to the upper handler) you may/may'not do specific action on behalf of some tough exception, but in nested case you can do action by handling that specific situation.
Are there common ways of refactoring the code to avoid this?
If you have a poorly factored program that does what the you want and has no serious bugs, for god sake leave it alone! When you need to fix a bug or add a feature, you Refactor Mercilessly the code that you encounter in your efforts. Override the Exception Class in your custom Exception Handler and add some added features to handle your problem.
The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.
Hop this will help you.
You should do away with the exception nesting. You should either avoid chaining the exceptions in the first place, or (selectively) unwrap and then rethrow the nested exceptions further up the stack.
About handling legacy code I would recommend you have a look at the book covering the topic:
http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052
You dont even have to go through the whole book, just look at the things that concern you at the moment.
Also a good book regarding good practices is:
http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?s=books&ie=UTF8&qid=1356340809&sr=1-1&keywords=clean+code
The best approach when handling nested exceptions is refactoring the code and using runtime instead of checked exceptions, and handling those where needed. This way the code is more readable and easier to maintain.
Its depend on the Business logic. You may take action on the exception there itself or you may propogate it all the way upto caller and leave it to the caller for what action he want.
e.g. There are lot of third party API where they don't handle the exception but they throw it from method and hence facilitate API users to take actions as per their need.
e.q. oracle JDBC driver. Driver.getConnection() throws exception. Now caller/API user can handle it as per their need. One may just print stack trace, one may notify admin asking for his attention or one may choose just silently exit the application.
There are two approaches:
To generate a separate exception for each event.
To create a generic exception and describe what caused it
The first approach allows you to write different code for handling the different events, but it requires you to write lot of Exception classes and in some case it could be just too much.
The second approach is more concise, but it makes it difficult to handle the different situations.
As it happens very often in programming the best solution is in the middle, where you balance generating separate exceptions and using one exception for other cases.
The rule of the thumb in this case could be to generate a separate Exception class for the exceptions you want to handle specifically with separate code.
Similarly to the what to throw, we should also have control on what to catch. We can use two approaches for our catch blocks:
A single catch block for all. For example:
catch (Throwable e) {
throw new CommandExecutorException(e);
}
many catch blocks one for each Exception. For example:
} catch (ClassCastException e1) {
...
} catch (FileNotFoundException e) {
...
} catch (IOException e) {
...
}
The first approach is very compact but basically groups every exception in the same case, it's useful only in the situation where all the exceptions are managed equally and do the same thing.
This approach is generally discouraged as it gives no control on the exceptions being catched, leading sometimes to tough bugs, which are also hard to find.
The second approach requires more lines of code but you can execute different operations depending on the exception occurred. This approach is more flexible but in some cases leads your methods to be very long due to exception handling.

Why Would you catch Throwable and do nothing but print a stack trace?

I have tried looking for an answer to this on other threads, but so far I have only seen threads that state that catching Throwable is bad. My question is, is there ever a reason why you would WANT to do this and then do nothing in the catch block except print out the stack trace?
I was recently brought onto a project and given the task of cleaning up the error handling of an existing set of classes for a RESTful service. Several of the helper service classes have try/catch blocks that only catch Throwable and print out the stack trace, as shown below:
class MainService {
SubService1 s1;
SubService2 s2;
public doMainService() {
}
}
class SubService1 {
public int findSomething() {
try {
// Do Something
} catch (Throwable t) {
t.printStackTrace();
}
}
}
class SubService2 {
public int findSomethingElse() {
try {
// Do Something
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Is there a case that this is acceptable? Would it be better for the methods to throw Exception and not have the try/catch blocks?
This is almost never a good practice for a variety of well known reasons.
In particular, it doesn't distinguish between checked and unchecked exceptions and errors. More importantly, one of the effects of this code is allowing the application to execute beyond the exception handler which may result in all kinds of strange behavior due to violated invariants. In other words, since the exception caught may be really anything including violated assertions, programming errors, thread interruptions, missing classes, I/O errors, OOM conditions and even library and VM bugs, the program state is practically unpredictable beyond the exception handler.
In some rare situations broad exception handling may make sense. Imagine a server handling multiple independent requests. You may not want to crash due to a problem encountered while serving one of the requests. Since you do not rely on the state left after the exception handler, you can simply print the stack trace and let someone investigate while the server continues serving other requests.
Even in these situations one should carefully consider whether errors, e.g. VirtualMachineError should really be caught.
One reason that I think people do this is just because Java forces you to either surround calls that throw with a try/catch block, or add throws to the method declaration.
If you "know" that you're not going to have an exception occur, then it's kind of a way to prevent it from going up the chain (cause if you do throws, who ever calls your code needs to surround with a try/catch and so on), but if something does occur it'll dump it without crashing.
You might do that if you don't know any other way to get the stack trace and you want to know how you got to your current location. Not a very good reason, but a possible one. This doesn't seem to fit what you're looking at though; you seem to have been given code which doesn't crash but also doesn't do a good job with error handling.
I use it to see exactly where my program is crashing. So basically just for debugging. Also just to see if it's flowing in the way expected.
It is possible that they wanted to see the stack trace without crashing the program.
For example it can be appropriate for code executed by a thread to log exceptions but otherwise do nothing when it is unacceptable for the thread to crash since the next iteration (say where threads are taking items from a queue) may work as expected. This depends on the use case, but for a server you generally want the threads to be bullet proof and log any errors, instead of halting any further processing (but use cases may vary).
Most simplest example we come across in your problem is when it comes to close an input stream.Follwoing is the method declaration in InputStream class.
public void close() throws IOException
Althoug there is a possiblity to throw an exception when we call this method it would be no harm for the program execution.(Since we will not use that InputStream further) In that case we should only log the error and continue the program. But if you find out an exception which change the states of an object and then you must think about recovery code or halt execution.
Never do this (e.printStackTrace()). many IDE's default to it, but its horrible (many apps run with stderr redirected in ways that are not accessible, and thus, never seen). rules of thumb:
if you truly don't care about the exception (never, ever, ever, ever will care), catch it and do nothing with a big comment which says "we really, really don't ever care if this exception gets thrown"
if you never expect an exception to actually be thrown (the interface defines a checked exception, but you know the impl doesn't actually throw it), rethrow the exception as something like new UnsupportedOperationException("this should never happen", t) (that way if/when the underlying impl gets changed you find out about it sooner rather than later)
if you expect that the exception is unlikely, and you usually will not care about it, log it with a proper logging infrastructure (log4j, commons logging, or java.util.logging). that way it will most likely make it somewhere that you can see later if you decide that you actually do care about the exception after all.

In the multi-thread program like producer/consumer, what's the purpose of Swallowing InterruptedException

Some code simply call
catch (InterruptedException ex) {}, why?
This is usually a sign that the developer didn't know how to handle the Exception and thus just ignored it.
This is the sort of bad behaviour that results in some saying checked exceptions are a failed experiment. IMHO Developers should just learn to handle exceptions.
A better way to handle this exception is to either
pass it to the caller. i.e. don't catch it.
call Thread.currentThread().interrupt() so the interrupt is not lost.
If such an exception should be impossible, wrap it in a throw new AssertionError(ex)
That is used in situations where an exception may occur but the response to the exception is the same as normal continuation from the try block. A common example is calling sleep(). (However, that's actually often a bad example because being interrupted often signals that an operation should be abandoned.)
InterruptedException is what's called a checked exception. When added to a method you want to call, it's a way of signifying that you must account for this situation, namely that the time you need to process the results of the call may be pre-empted by another thread in the system.
Assume for the moment that you have 6-7 statements in a try block, and you assume they will run in a more or less atomic fashion. Among those statements is one that relies on thread-aware behavior. If that call is pre-empted, your subsequent statements won't run, and you'll have to handle the consequences.
People have all sorts of reasons for catching this exception but taking no action. I can't think of many good reasons for doing this, unless I can clearly show that being interrupted doesn't create an undesirable side-effect in my code. Given any example piece of code that shows this behavior, I would guess no catch logic was included because a) the programmer had no plan for dealing with it; b) the programmer merely wanted to step past the check so the code compiles.

Java Exceptions, What to catch and what not to?

I keep getting the dreaded java.something.someException errors while running my java app. and I don't seem to be getting the hang of what exceptions to handle and what not to?
When I read the api docs most of the functions throw exceptions like if I use I/O or use an Array... etc.
How to make a decision about what exceptions to catch and what not to and based on what parameters?
I am talking about checked exceptions here.
Short answer
Catch exceptions that you can deal with then and there, re-throw what you can't.
Long answer
It's called exception-handling code for a reason: whenever you are tempted to write a catch block, you need to have a good reason to catch the exception in the first place. A catch block is stating your intent to catch the exception, and then do something about it. Examples of doing something about it include, but are not limited to:
Retrying the operation that threw the exception. This can make sense in the case of IOException's and other issues that may be temporary (i.e. a network error in the middle of trying to upload a file to a server. Maybe your code should retry the upload a few times).
Logging the exception. Yes, logging counts as doing something. You might also want to re-throw the original exception after logging it so that other code still has a chance to deal with the exception, but that depends on the situation.
Wrapping the exception in another exception that is more appropriate for your class's interface. For example, if you have a FileUploader class, you could wrap IOException's in a more generic UploadFailedException so that classes using your class don't have to have detailed knowledge of how your upload code works (the fact that it throws an IOException is technically an implementation detail).
If the code can't reasonably do anything about the problem at the point where it occurs, then you shouldn't catch it at all.
Unfortunately, such hard-and-fast rules never work 100% of the time. Sometimes, a third-party library you are using will throw checked exceptions that you really don't care about or which will never actually happen. In these cases, you can get away with using an empty catch block that doesn't run any code, but this is not a recommended way to deal with exceptions. At the very least, you should add a comment explaining why you are ignoring the exception (but as CPerkins notes in the comments, "never say never". You may want to actually log these kinds of "never-going-to-happen" exceptions, so just in case such an exception does happen, you are aware of it and can investigate further).
Still, the general rule is, if the method you are in can't do something reasonable with an exception (log it, rethrow it, retry the operation, etc.) then you shouldn't write a catch block at all. Let the calling method deal with the exception. If you are dealing with checked exceptions, add the checked exception to the throws clause of your method, which tells the compiler to pass the exception upwards to the calling method, which may be better suited to handle the error (the calling method may have more context, so it might have a better idea of how to handle the exception).
Usually, it is good to put a try...catch in your main method, which will catch any exceptions that your code couldn't deal with, and report this information to the user and exit the application gracefully.
And finally, don't forget about finally
Also keep in mind that even if you don't write a catch block, you might still need to write a finally block, if you need clean-up code to run regardless of whether the operation you are trying to perform throws an exception or not. A common example is opening up a file in the try block: you'll still want to close the file, even if an exception occurs, and even if your method isn't going to catch the exception. In fact, another common rule of thumb that you might see in tutorials and books is that try...finally blocks should be more common that try...catch blocks in your code, precisely because catch blocks should only be written when you can actually handle the exception, but finally blocks are needed whenever your code needs to clean up after itself.
I highly recommend chapter 9 (Exceptions) in Joshua Bloch's Effective Java, 2nd Edition for these questions.
A general rule of thumb is to handle those exceptions that you can do something about and don't handle those that you can't. In the cases where you don't handle an exception the caller is expected to handle them. If you're writing a framework or a library usually you'll end up wrapping low level exceptions like SQLException in a library or framework specific exception to abstract away the lower level details.
For example, if you're writing a method that writes to a file on disk then you should probably handle FileNotFoundExceptions since you can create the missing file, but if you run into problems creating the file or writing to it then you should probably let the caller handle it (after performing whatever cleanup work needs to be done).
These are my personal findings:
You need a try {} catch (Throwable o) {...} in your main routine so any unexpected exception can be caught, logged and the user told.
Checked exceptions are checked because you need as a programmer to make a decision what to do when they happen. Remember, one decision might be just to say "ok, time to crash".
If you end up with a fatal situation with a checked exception where all you can do is crash, then "throw new RuntimeException("reason", checkedException);" so the handler above have something to log. Include value of important local variables - remember some day you will have to debug a situation where the only thing you have is the stack trace.
Never, ever catch an exception and just ignore it. If you have to then you must document why you are allowed to break the rule, and do it right there, in the catch block.
And a hint that will help you some day: When you crash, provide a simple means to let the user seeing the message email the stack trace to you.
EDIT: Do not be afraid to create new exceptions if the ones available does not completely cover what you need. This allows you to get better naming in stack traces and your error handling code can differentiate between different cases easily. You may want to base all your own exceptions on a common base class ("OurDomainException") so you can use the base class in catch clauses to see if what type it is.
Having coded in Java for a few years, I agree that it is easy to get annoyed by writing endless try-catch blocks.
A good way of coding fast is to catch specific exceptions in as low level as you can, and catch the base Exception at the outermost level (in main()) just so that you can write a generic error message instead of letting the program crash.
This lets you have a running code pretty fast, and then you can take your time to add specific exceptions in various layers with their handling logic.
Catch checked Exception, do not catch RuntimeException. Try to catch specific Exception, try not to catch by generic java.lang.Exception.
Module boundaries
I catch exceptions for cleaner module boundaries, too. For example if there is a SQLException thrown that I can't handle I'll catch it nevertheless and throw my own descriptive exception instead (putting the SQLException as cause). This way the caller doesn't have to know that I'm using a database to fulfill his request. He just gets an error "Cannot handle this specific use case". If I decide to fulfill his request without database access, I don't have to change my API.
As a rule of thumb I catch exceptions where I will be able to do something with then, or where I want the exception to stop moving up. For example, if I am processing a list of items, and I want the next item to be processed even if the others fail, then I will put a try...catch block around that item processing and only in there. I usually put a try...catch(Throwable) in the main method of my program so I can log errors like a class not found or similar stuff.
I don't put a try...catch block in a method if I will not know what to do with that exception. If you do, you will just bloat your code with lots of exception handling code.

Categories