beginner question about exception in java - java

when an exception occurs that a method is unable to handle - does the program terminate and show the error number ? where does the error number and information about the error come from ? should the programmer while coding have an idea what kind of exception might occur. if so why does'nt he ensure that exception does not occur .

If you are using Java APIs, the exceptions that each method throws are documented.
When the program terminate, it shows an stacktrace of the methods calls that caused that specific problem.
Check the lesson on Exceptions from The Java Tutorial. You can learn much more reading there than reading my answer here :)

There are 2 main types of exceptions in Java:
- checked
- unchecked
unchecked exceptions are further broken into RuntimeException and Error.
RuntimeExceptions are programmer errors (ArrayIndexOutOfBoundsException) and Errors are things that are problems in the VM (OutOfMemoryError).
You should not catch RuntimeExceptions - you should fix your code so it does not throw the exception.
You should not catch Errors since the VM is likely in a state that you cannot do anything to recover from them.
If your main does not catch an unchecked exception it will crash.

Java Exceptions bubble-up to the point where someone catches them, or to the point the program exits.
In the real-world, when many frameworks are used, exceptions never bubble-up to the top. They are caught and reported (printed on console). Catching exceptions is done by the try { } catch(..) { } block.
There are two types of exceptions - checked and unchecked. The checked exceptions must be declared in the method signature (unlike the unchecked)

should the programmer while coding
have an idea what kind of exception
might occur
Yes, but no one's perfect.
why does'nt he ensure that exception
does not occur
In exceptional circumstance, you WANT an exception. You do not want to ignore the exception.
For example, suppose that your program creates a file to save user settings. If for some reason
the file creation fails (which your program has no control over, it's the Operating System's job), you do not want to go on like nothing happened. You want there to be an exception, so that whoever or whatever function called that function knows about this problem, and can do something, e.g. inform the user.

Related

How to handle Runtime Exception in Real life projects [duplicate]

This question already has answers here:
When is it OK to catch a RuntimeException
(10 answers)
Closed 5 years ago.
Recently I was at an interview and the interviewer asked me regarding exception handling. I gave the typical checked unchecked answer. Then He asked me should you handle runtime exception ? I said no and then it was asked that if we get a NullPointerException suppose, will you send the same to the user ?
I got confused. So what I am looking for is that, should we catch runtime exceptions or not ?
If Yes, How can we do that ?
If No, then do we show java.lang.nullpointerException to the user ?
Thanks in advance.
The best way to handle any predictable RuntimeException is to catch it and produce user-friendly information about what happened with probable causes and what the system expects the user to do next.
Suppose if you have a project that provides the user with a UI based calculator. Now, what should ideally happen if the user enters a 'division with zero' instruction? Say if you are not checking for the 0 denominator (which of course is not advisable), your program will throw an ArithmeticException. How should you handle it? You should catch it and let the user know that he has entered an input which the system was not expecting, i.e.
You cannot divide by zero. Please enter a non zero denominator!
If it is an API and is to be consumed by another application, what I would do is to wrap the runtime exception into a customized API specific exception and throw it from there, so that the implementor can use the information and handle it in a suitable fashion. e.g.
public int divide() throws InvalidArgumentsException
Your average user isn't going to know what the NullPointerException is or how/why it happened. You would usually present the user with a more friendly error, perhaps with an error code they can provide to help identify the error.
The application may also save the NullPointerError along with the stack trace to a file so a developer can see exactly where the error occured.
You can catch RuntimeExceptionclasses in your Application by implementing a UncaughtExceptionHandler:
Thread.setDefaultUncaughtExceptionHandler(Thread t, Throwable e) -> {
// log Exception to file, send to server ecc, you can check which exception was thrown and act accordingly...
// you can still re-throw the exception here as if this block did not exist
});
This method should catch all uncaught Exceptions, even those that were thrown by other Thread instances, so it's safe to just use one implementation.
You question:
should we catch runtime exceptions or not
It depends; you don't want a whole Banking Application Server crash, just because it could not find a file in the file-system.
At the same time, RuntimeException's usually happen because there is a flaw in the code. NullPointerException's can be avoided, as well as many others...

How can I make program print a stack trace automatically when an Exception occurs in Android

Is there a way I can automatically print a stack trace when Exception occurs? I understand I can do so by manually surrounding a block with a try-catch statement, but there's no prior-knowledge where an exception would happen in a program, and doing it in suspicious region block by block would be super inefficient, since there're potentially many. So is there any configuration option or any programmatic way to do so in Android?(like surrounding a try-catch block in the highest level of method?, but what's the highest level of method)
Define a global exception handler in your Application class and add any code you need to it.
Thread.setDefaultUncaughtExceptionHandler(
new DefaultExceptionHandler(this));
It is recommended that you still re-throw caught exceptions so that the app stops running, because it will be in an unstable state and not doing so can cause the app to freeze up.
catch (Exception e) {e.printStackTrace();}
The highest level is the Application level I believe. But in general just catch it at the usual activity lifecycle should be sufficient.
Extend Exception and do whatever you want in your custom Exception class.
There are two major kinds of exceptions:
Exceptions caused by programming errors (e.g. dereferencing a null reference, ...)
Exceptions caused by the environment (e.g. user enters 'abc' in a numeric field, network cable was unplugged, ...)
In most of the cases you can't really recover from the first ones. (If something unexpectedly went wrong, how can you know what to do to recover safely?) This are usually unchecked exceptions and you don't have to catch them somewhere.
Uncaught exceptions are catched by the system/framework and logged automatically!
Take care for the second type of exceptions! They are mostly not unchecked and have to be either cached or specified via throws clause. Handle them, probably log them, and try to recover if possible.
This document explains how you can read the error log and other logs on android devices. There are also apps available that can display the log on the device itself.
Also read this basic exception tutorial!

When to catch RuntimeExceptions in code? [duplicate]

This question already has answers here:
When is it OK to catch a RuntimeException
(10 answers)
Closed 7 years ago.
While programming in java is there any time that I as the programmer should be considering to catch RuntimeExceptions ?
You catch RuntimeException for the same reason that you catch any exception: you plan to do something with it. Perhaps you can correct whatever caused the exception. Perhaps you simply want to rethrow with a different exception type.
Catching and ignoring any exception, however, is extremely bad practice.
This is what I can think of.
If you want to show a nice message to the end user in case something has gone wrong, catch the RuntimeException and log it. Then show some nice message in the screen instead of a blasting error.
To wrap the framework specific CheckedExceptions to application specific RuntimeExceptions.It is preferred to use the RuntimeException as your custom exception as told here.
Based on user validation if want to show custom message to the user then go for RuntimeException.
Wrap your custom message in then throw it.
throw new RuntimeException("Invalid userName/Password !");
Basically, the only time you would want to catch one is when you cannot allow your application to blow up. This is a good article describing this in much more detail, but here is a quote that sums it up:
"If a client can reasonably be expected to recover from an exception, make it a
checked exception. If a client cannot do anything to recover from the exception,
make it an unchecked exception".
Since unchecked exceptions are basically just bugs in your code and by really should only be thrown where there is nothing that can be done about them, the only real time that you would want to catch one is when you cannot allow your application to blow up.
Yes: whenever you can and want to recover from them.
Many common exceptions inherit from RuntimeException and each may or may not be recoverable depending on the particular circumstances. The RuntimeException class itself does not imply that the exception must or must not be caught.
For example, you may have a library method which throws IllegalArgumentException on certain inputs. If applicable to your program, you could catch this exception and recover in some way, for example by trying a different input, or explaining to the user why the operation cannot continue.

When is it OK to catch a RuntimeException

On a recent project I recommended catching a RuntimeException within a test harness code and logging it. The code processes a series of inputs from a database, and I do not want the test to stop due to failure of any one input (Null values, Illegal arguments, etc.). Needless to say, my suggestion triggered a passionate discussion.
Is catching any kind of RuntimeException acceptable? If yes, what are other scenarios where it is OK to catch RuntimeExceptions?
You catch RuntimeException for the same reason that you catch any exception: You plan to do something with it. Perhaps you can correct whatever caused the exception. Perhaps you simply want to re-throw with a different exception type.
Catching and ignoring any exception, however, is extremely bad practice.
Unless you can correct a RuntimeException, you don't want to catch it...
...only true from a developers point of view....
you have to catch all exceptions before they reach up to the UI and make your user sad. This means on the "highest level" you want to catch anything that happend further down. Then you can let the user know there was a problem and at the same time take measures to inform the developers, like sending out alarm mails or whatever...
It is basically considered a data/programming error that could not be forseen, thus you want to improve future releases of the software while at the same time take the user by the hand and move on in a controlled manner...
RuntimeException is intended to be used for programmer errors. As such it should never be caught. There are a few cases where it should be:
you are calling code that comes from a 3rd party where you do not have control over when they throw exception. I would argue that you should do this on a case by case basis and wrap the usage of the 3rd party code within your own classes so you can pass back non-runtime exceptions.
your program cannot crash and leave a stack trace for the user to see. In this case it should go around main and around any threads and event handling code. The program should probably exit when such exception occurs as well.
In your specific case I would have to question why you are having RuntimeExceptions occur in the tests - you should be fixing them instead of working around them.
So you should guarantee that your code only throws RuntimeExceptions when you want to have the program exit. You should only catch RuntimeExceptions when you want to log it and exit. That is what is in line with the intent of RuntimeExceptions.
You can look at this discussion for some other reasons that people give... I personally haven't found a compelling reason in the answers though.
In my code 99% of my exceptions are derived from runtime_exception.
The reasons I catch exceptions are:
Catch Log and Fix problem.
Catch Log and Generate a more specific exception and throw
Catch Log and rethrow.
Catch Log and Kill operation (discard exception)
User/request initiated action fails.
An HTTP request handler for example. I would rather the requested operation die rather than bring the Service down. (Though preferably the handler has enough sense to return a 500 error code.)
Test case passed/failed with an exception.
All exceptions not in the main thread.
Allowing exceptions to escape a thread is usually badly documented but usually causes program termination (without stack unwinding).
Years ago, we wrote a control system framework and the Agent objects caught runtime exceptions, logged them if they could and continued.
Yes we caught Runtime exceptions including OutOfMemory in our framework code( and forced a GC, and it's surprising how well that kept even quite leaky code running.)
We had code that was doing very mathematical things involving the real world; and from time to time a Not-A-Number would get in due to tiny rounding errors and it coped okay with that too.
So in framework / "must not exit" code I think it can be justifiable. And when it works it's pretty cool.
The code was pretty solid, but it ran hardware, and hardware tends to give screwy answers sometimes.
It was designed to run without human intervention for months at a time.
It worked extremely well in our tests.
As part of the error recovery code, it could resort to rebooting the entire building using the UPS's ability to turn off in N minutes and turn on in M minutes.
Sometimes hardware faults need to power cycled :)
If I remember, the last resort after an unsuccessful power cycle was it sending an email to it's owners, saying
"I tried to fix myself and I can't; the problem is in subsystem XYZ", and included a link to raise a support call back to us.
Sadly the project got canned before it could become self aware :)>
Personally, I've always been told that you want to catch all RuntimeExceptions; however, you also want to do something about the exception, such as running a failsafe or possibly just informing the user that an error occurred.
The last Java project that I worked on had a similar approach, at the very least, we would log the exception so that if a user called complaining about a bug, we could find out exactly what happened and see where the error occurred.
Edit 1: As kdgregory said, catching and ignoring are two different things, generally, people are opposed to the latter :-)
We all know that checked exceptions and RuntimeExceptions are the two categories of exceptions. It is always suggested that we handle (either try-catch or throw) the checked exceptions because they are the programming conditions where unfortunately programmer can not to do anything on its own;
Like FileNotFoundException it is not the programmer who puts files on user's drive if program is actually trying to read the file 1.txt which is supposed to be there on f:\ of user with the statements:
File f11 = new File("f:\\1.txt");
FileInputStream fos = new FileInputStream(f11);
If the file is found it's all ok, but what happens in the other case if the file is not found is that, program crashes down with 0 error from the user. In this scenario programmer did not do anything wrong. This could be a checked exception which must be caught for the program to continue running.
Let me also explain the second scenario with which the concept of RuntimeException will be clear. Consider following code:
int a = {1,2,3,4,5};
System.out.println(a[9]);
This is poor coding which generates the ArrayIndexOutOfBoundsException. Which is an example of RuntimeException. So programmer should not actually handle the exception, let it crash the program, and later fix the logic.
You catch RuntimeException when you want to process it. Maybe you want to rethrow it as a different exception or log it to a file or database, or you want to turn on some exception flag in the return type, etc.
You catch RuntimeExceptions (in any language: unexpected exceptions/“all” exceptions) when your program is doing multiple subtasks and it makes sense to complete every one you can rather than stopping on the first unexpected situation. A test suite is a fine situation to do this — you want to know which of all the tests failed, not just the first test. The key characteristic is that each test is independent of all the others — it doesn't matter whether a previous test doesn't run because the order is not significant anyway.
Another common situation is a server; you don’t want to shut down just because one request was malformed in a way you didn't expect. (Unless it’s really, really important to minimize the chances of inconsistent state.)
In any of these situations, the appropriate thing to do is log/report the exception and continue with the remaining tasks.
One could vaguely generalize to any exception: it is “appropriate to catch” an exception if and only if there is something sensible to do after catching it: how your program should continue.
If a client can reasonably be expected to recover from an exception, make it a checked exception.
If a client cannot do anything to recover from the exception, make it an unchecked exception.
Here's the bottom line guideline.
From Java Docs. Please read this Unchecked Exceptions — The Controversy

Why does Java have both checked and unchecked exceptions? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
When to choose checked and unchecked exceptions
Why does Java as a language have both checked and unchecked exceptions. What purpose do they serve?
Note: I'm not asking when I should use them, or how to code them, but what they add to the language.
The theory for checked exceptions is simple.
When designing an interface, think of exceptional cases that can occur, and will occur, with the normal state of a method call. Declare these exceptions in your interface, as the programmer will have to handle them directly.
For example, a bank account withdraw method may declare an OverdraftException, which is an expected exception - a withdrawal may fail due to overdraft, but this type of failure may be handled differently by the client code (one may decide to completely deny the withdrawal, another may decide to apply a huge penalty and allow for a negative balance to be recorded, another may decide that their client is allowed to draw from a different account).
However, runtime exceptions were supposed to be programming errors that weren't supposed to be handled directly - such as NullPointerExceptions, which only occur if methods take invalid arguments or don't check for such cases directly.
This is a good theory. However, Java messed up with its implementation of Exceptions, and this threw the book of this theory out the window.
There are two cases that I will illustrate where Java messed up with its implementation of Exceptions. These are IOException and SQLException.
An IOException occurs anytime, anywhere a stream in the IO libraries of Java messes up. This is a checked exception, however. But, generally you cannot do anything but log that an error occur - if you're simply writing to the console, what can you reasonably be expected to do if you suddenly get an IOException when you're writing to it?
But there's more.
IOException also hides stuff like file exceptions and network exceptions. They may be subclasses of IOException floating around for that, but it is still a checked exception. If your writing to an external file fails, you can't really do much about it - if your network connection is severed, ditto.
SQLException is the same way. Exception names should show what happened when they are called. SQLException does not. SQLException is thrown any single time any possible number of errors are encountered when dealing with a database - MOST OF WHICH THAT HAVE NOTHING TO DO WITH SQL.
Therefore, programmers typically get annoyed with handling exceptions, and let Eclipse (or whatever IDE they're using) generate blocks like this:
try {
thisMethodThrowsACheckedExceptionButIDontCare();
}
catch(Exception e) {
e.printStackTrace();
}
However, with RuntimeExceptions, these intentionally bubble up and eventually get handled by the JVM or container level. This is a good thing - it forces errors to show up and then you must fix the code directly instead of ignoring the exception - you may still end up just printing the stack trace (hopefully logging it instead of printing to the console directly), but then there will be an exception handler that you were forced to write because of a real problem - not because a method said that it might possibly throw an Exception, but that it did.
Spring uses a DataAccessException to wrap SQLExceptions so that you don't have to handle them as a checked exception. It makes code much cleaner as a result - if you expect a DataAccessException, you can handle it - but most of the time you let it propagate and be logged as an error, because your SQL should be debugged by the time you release your application, meaning the DataAccessException is probably a hardware issue that you could not resolve - DataAccessException is a much more meaningful name than SQLException, because it shows that access to data failed - not that your SQL query was nessecarily at fault.
They add a differentiation between errors that the designer of a library feels must be caught, and ones that they feel the programmer shouldn't handle.
For example it might be reasonable for a program to handle bad input from a user, but if something goes wrong with the underlying OS and threads starts to die without reason, it isn't something that the program should be expected to handle.
Personally, I think checked exceptions were a mistake in Java.
That aside, designating both checked and unchecked exceptions allows a library to differentiate between recoverable and unrecoverable errors. By making all recoverable errors throw checked exceptions, a library/language can force a developer to handle the edge cases they might otherwise paper over.
The big problem with this:
try{
myCode();
}catch(Exception e){ //Do nothing }
Additionally, in most cases it really is best to just throw up your hands and pass an exception up when one occurs. By forcing checked exceptions to be declared, a method that really doesn't care if an error occurs ends up having dependencies (in terms of compatibility, but also code-smell and others) it really shouldn't.
I think Sun initially thought it would be a good idea because the programmer is forced to handle the exception. However, many years later, pretty much everyone agrees they are a bad, unneccessary addition.
One of the main issues (apart from cluttering code) is that they leak abstractions form lower layers to higher layers (such as rmi remote exceptions)
Checked and unchecked exceptions invokes a bit of a religious argument - Java fell one side of the fence, C# the other.
In Java checked exceptions should be used when the calling code can recover from the error as where unchecked exceptions are used when there's a critical error (with perhaps the exception - no pun intended - of NullPointerException) that the calling code is unlikely to be able to recover from.
Personally I like to have both available to me generally favouring checked exceptions because they allow me to force the calling code to deal with an error situation that a developer might otherwise have ignored (although the infamous empty catch block side-steps this).
I don't think there's anything at all conceptually wrong with checked exceptions... but they do tend to suck mightilly in practice, because (especially early) library developers over-use them.
Also the "catch or declare" requirement does NOT fit well with interfaces.
My basics thoughts are: "Stuff that goes wrong" comes in two basic flavours: recoverable, and unrecoverable... Ergo: Business Exceptions and System Errors.
For instance: What do you (the library developer) expect me (the application programmer) to do about recovering from a failure in a call to SomeStream.close()? Yes, I definately need to be made aware that something has gone horribly wrong, but really my only option is to terminate the program/request/process/thread which tripped over it. I cannot be reasonably expected to even attempt to recover from the situation... Ergo: It's an uncoverable error, and therefore I shouldn't be forced to write a lot of highly repitious boilerplate catch-blocks which don't handle the problem at every level of the (potentially very deep) callstack. Therefore I believe it would be better if "catch all" checked exceptions such as IOException had never been invented... CloseException extends UncheckedIOException would be more appropriate, IMHO.
Also, if I had a time machine I'd go back in time and plead with the Java gods for:
interface Throwable
abstract class Exception
abstract class CheckedException
abstract class UncheckedException
class Error
Also: I'd love to see a #FaultBarrier class-annotation, which makes the compiler enforce: All exceptions (especially unchecked ones) must be caught or explicitly thrown. The most horribilest hunk of system I've ever worked on was riddled with throwings of raw RuntimeException; It's enough to make you weep.
Cheers. Keith.

Categories