Using exception or using multiple try catch java [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am just writing a code and want to know whether it is good to use exception class to catch an exception or using multiple type of try-catch.
try{
// some error-prone code
}catch(Exception e){
}
or,
try{
// some error-prone code
}catch(NullPointerException n){
}catch(ArrayOutOfBoundException a){
} ..... etc

It depends on what will you do with the exception. If you have specific things to do per exception then you can use multiple try catch. If not you can just use the generic exception. Also if you know what kind of exception your code might throw better just use that specific exception.

You should only catch exceptions that you know how to process properly; examples include IOException where you can do something like retry an operation, return some default value, or rethrow the error; and NumberFormatException, where you're trying to read user input as a number and find that it's garbage, so you can ask the user to try again.
In nearly all cases, you don't actually know what the proper response to "any error" is, and in many cases (most unchecked exceptions, for example), the only thing you'll be doing by catching Exception is masking some underlying problem that needs to be resolved. In general, the only response that is acceptable for a generic unknown exception is "write a log message and abort the current operation" for whatever definition of "current operation" applies (might include things like rolling back a transaction and returning an HTTP 503 status code).
In real-world applications, this last-resort catch Exception is handled by framework code (such as Spring or Jersey) and does these broad cleanup operations. If your code can't do anything better (which generally requires knowing what specifically happened, not just "an exception"), then it should let the exception propagate and use the standard error handlers.

Related

Are lots of exceptions bad design in Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am currently wrapping a C Library in Java, making it easier to use and work within OO-Programming. The C Library uses error codes (int return value) and Out-Parameter for data manipulation. I am not necessarily a fan of error codes, so I would like to create some custom Exception classes that I can throw if my library detects an error code other than "success".
The only problem is that the amount of Exceptions that might be raised by every single method is very high (There are some error codes that can be returned from every C library function, like "Device_Not_Connected"). It has been a while since I last programmed in Java, so, I really don't know what the situation is with Exceptions in Java.
Are methods that throw a lot of different exceptions bad design?
Do I have to handle the exceptions, or is there a way of simply ignoring it?
If I can ignore an exception, does it bubble up the call tree (like in Python for example)?
Are there any alternatives to exceptions in Java besides error codes and no-ops?
Are methods that throw a lot of different exceptions bad design?
If used right clearly no! An exception basically is just a possible return state which is out of the scope of the technical purpose of the method. E.g. if the method should read an value from a device null or any value should be returned using the return type. But throwing a custom DeviceNotConnectedException to state that something went wrong when you are not able to read a return value instead of simply returnung null is 100% best practice. And if 10 things can go wrong then it is okay to state 10 possible exceptions.
Do i have to handle the exceptions, or is there a way of simply ignoring it?
When you don't catch an exception you will have to declare the method it occurs in with "public void myMethod() throws MyExcp {..}" and so on in every method calling this method, that method caller and so on. If you hand it to the main-method and it's not handled there it will crash the programm.
If i can ignore an exception, does it bubble up the call tree (like in Python for example)?
See above.
Are there any alternatives to exceptions in Java besides error codes and no-ops?
Not as far as I know but I'm not an expert.
You should definitely throw an exception if something goes wrong that is connected to IO (files, devices, user input). You do not need to define a different exception class for all the different error codes. If the handling of the error codes is quite similar, you can use the same exception, like
throw new IOException("Device not connected");
If possible, you should avoid throwing around too many exceptions that are connected to wrong parameters etc. Establish check functions for the user (like "containsKey") so that need not "try and catch" such things.
You could create an inheritance hierarchy for your Exception classes, so that a method signature defines few [or even only one] general Exception class, regardless how many specific Exceptions you throw in the method's body.
public void myMethod() throws MyGeneralException {
...
throw new MySpecific1Exception();
.....
throw new MySpecific2Exception();
}
The callers will have the freedom of choice to handle specific Exceptions or the general ones.
Option 1:
try {
myMethod();
} catch (MyGeneralException e) {
....
}
Option 2:
try {
myMethod();
} catch (MySpecific1Exception e) {
....
} catch (MySpecific2Exception e) {
....
}

Runtime exception and Checked exception [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
There are so many exceptions, and it is not easy to remember. Is there any rule to know which kinds of exception will fall in which type (runtime vs checked), so that we know in which case we need to catch and in which case we just throw an exception? Thanks!
First of all, no exceptions are compile-time exceptions. The differentiation is checked exceptions vs. unchecked exceptions. The differentiation is made by the compiler by behaving as if each and every operation (method, constructor and initializer block) signature always implicitly includes throws Error, RuntimeException in its declaration. This way, the handle-or-declare rule, which means the compiler forces you to either handle an exception in a catch clause or declare an exception with a throws declaration is disabled for Error and RuntimeException - they are always implicitly declared.
So we overall have the following categories:
Compiler-treatment:
unchecked exception (handling is optional): RuntimeException and Error
checked exception (handle-or-declare rule applies): All other exceptions, including Throwable.
Categories:
Error - we usually do not catch these.
RuntimeException - catching depends on root cause.
Exception - we must handle or declare them (compiler enforces).
Error is easy to remember. If the VM or one of its APIs thinks it's a defect of the VM or the API that causes the issue, it's an Error. Usually we do not catch Errors, although there are a few prominent examples, like these:
catching OutOfMemoryError in resource allocating code to let the application continue after displaying an error message to the user. I.e. the user wants to load an image that's too big.
catching AssertionError in Unit Test frameworks. (They actually catch Throwable, but AssertionError is treated specially, it's a test failure, not a test error.)
Runtime exceptions are exceptions which do not happen if the program was written correctly, as long as the conditions that could lead to these exceptions do not depend on the user. For example, Integer.parseInt(String) throws NumberFormatException. If the String that is converted is coming from the program itself, it should be correct and we wouldn't care about the exception. If the String that is converted is coming from the user, we would usually rather catch NumberFormatException than letting the user crash the program by means of faulty input.
Other exceptions are used where the fault condition is somewhat likely but the program is always expected to handle them in some way. For example, if you open a file, it could always be that the file doesn't exist, cannot be read due to lack of permissions or locking, or that the storage is corrupt.
If you want to be new about things just catch everything... (horrible idea though only for the lazy) Otherwise look at the javados and it will tell you what is throw with each method.
try {
// this code
} catch (Exception e) {
e.printStackTrace();
}
Yeah if you have an issue at compile it means it just doesn't compile therefore doesn't exist and cannot run.
Do not catch RuntimeExceptions and Errors, catch other exceptions or add throws to method declaration

Is there any case when NPE and IAE get handled differently? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Concerning the holy war question about choosing the proper exception in case of a null argument, I wonder if this choice has any practical consequences. I mean, is there a case when you'd catch a NullPointerException and not IllegalArgumentException, or vice versa, or catch both and handle them differently?
To make it clear: This is definitely not the linked question. I'm not asking what exception to throw... I'm asking if they ever get handled differently. I know that with both being RuntimeExceptions they hardly ever get caught, but sometimes you have to do it.
The intent of both exceptions is quiet different
NPE - in most scenarios that I can think of it occurs due to programming errors, so should not be handled.
In case of null, NPE should be thrown in a fail fast manner as it affects the trace. For which I personally use Preconditions.checkNotNull(E ref, String message) of Guava.
IAE - This means there that the class did not expect such a value from the caller. There can be scenarios when you can catch that exception and use default value for recovering.
I know that with both being RuntimeExceptions they hardly ever get
caught
According to me this is quite a misconception that Runtime exceptions are hardly ever caught. Nowadays APIs are depending more on Runtime exceptions as they want to leave on the caller to decide whether the exception gets caught. Many APIs impose you to catch many exceptions which leads to a lot of pain when you know that exception is never going to occur. You are forced to catch it and leave an empty catch block or better log that it should not occur.
The APIs do however specifically document when a particular exception is meant to occur.
Take an example of Integer.parseInt(String s) which throws NumberFormatException and which is a Runtime exception, in most scenarios when I have used it I always catch it and do some recovery using default values.
Think of the scenario if NumberFormatException would have been a checked exception, and you making a call Integer.parseInt("1"), it is clearly visible that it won't occur but still you will be forced to catch it. Agreed that the example is a hypothetical one, but gets my point through.
Again this is just my opinion based on my experience.
I'm asking if they ever get handled differently.
As I have wrote NPE is not caught in most scenarios, but there are always exceptions. Like suppose there is a part of your system that is kept open for extension for someone else to program and there is NPE in that code and you don't want the upper layers to be affected by it then I catch NPE and remove that component from the system giving proper logs and traces. A concrete example is a pluggable system, I didn't want my whole system to crash due to programming error in a user written plugin. So I caught Exception. This may be a bad example for others but worked for me.
IllegalArgumentException can be caught when sanitizing a user input based on criteria known only in the throwing method. It is a more subjective notion, and therefore I sometime catch it.
null you can always test yourself.
I don't think there is any difference from a technical point of view. I'd say stick to a strategy and document it as best as you can. Moreover, these are runtime exceptions, so they are not meant to be caught as they should happen in case of bugs or when a client calls a method/service without providing all the required parameters. Let it crash!
About the holy war question, I do believe NPE should only happen when a client tries to access a variable they think is not null but is, indeed, null and thus never thrown directly. IAE is more appropriate if a client expects a non null value and receives a null from a caller. This is IMO, don't want to take part in the feud.

How to handle exceptions when programming with Java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am studying Java these days, and I have realized that it is important to handle exceptions in my codes.
I just what to ask how to handle exceptions with various methods?
Is it to examine the method I use to see what exception the method has thrown? In the example below I have to see what exception method m() throws.
try {
m();
} catch(SomeException e) {
...;
}
Is there any train of thought to handle exceptions when programming with Java?
The main skill to learn is how to not catch exceptions, but let them propagate up the call stack into the exception handler at the appropriate level.
Some rules of thumb:
catch the exception early (close to where it appeared) only if you have an actual escape route, a different way to complete the request in progress;
either log the exception or rethrow it, never both;
the place high up in the call stack is called the exception barrier: this is the unique place where to log the exception as an error;
don't be mislead by checked exceptions: most of the time the checked/unchecked distinction is not salient. Rethrow the checked exception (wrapped in a RuntimeException) when you have no code in mind to recover from it, which is the case most of the time. You could also declare the exception in your method header, but that is rarely practical;
be very careful not to let an exception result in a resource leak: all the acquired resources must be released in the finally block.
Reading these lines you'll note that most issues around exceptions are not demonstrable on minimal, textbook examples. Exceptions are about the information and control flow in fat codebases.
You really need to do a few tutorials on exception handling, you could use:
try {
m();
} catch(Exception e) {
e.printStackTrace();
}
to see what exception is being thrown and then read up on it.
Usually you need to log the exception, at least. And when
catching the exception make sure your catch block is not empty.
Some of them you can handle, some you cannot (for them you
usually need to fix your code as they indicate a bug in it).
So some are expected, others are programming errors.
Some are RuntimeExceptions (unchecked), others are not RuntimeExceptions
(i.e. are checked). RuntimeExceptions you don't need to declare in methods
or catch (i.e. you're not forced to do so by the language itself).
http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
http://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html
The subject is too broad.
Try with samples like this as mentioned in below links that will give you clear clarification about the exception handling Do it with practically bro...
The 'Throwable' class is the superclass of all errors and exceptions in the Java language
Exceptions are broadly classified as 'checked exceptions' and 'unchecked exceptions'. All RuntimeExceptions and Errors are unchecked exceptions. Rest of the exceptions are called checked exceptions. Checked exceptions should be handled in the code to avoid compile time errors.
Exceptions can be handled by using 'try-catch' block. Try block contains the code which is under observation for exceptions. The catch block contains the remedy for the exception. If any exception occurs in the try block then the control jumps to catch block.
If a method doesn't handle the exception, then it is mandatory to specify the exception type in the method signature using 'throws' clause.
We can explicitly throw an exception using 'throw' clause.
http://java2novice.com/java_exception_handling_examples/
http://www.programmingsimplified.com/java/tutorial/java-exception-handling-tutorial

Should IndexOutOfBoundsException be checked? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I recently tracked down a bug where a list was of length 0 but an access attempt was made at position 1
System.out.println("key is " + keyValuesPairs.get(0)+ " , value is " + keyValuesPairs.get(1));
This caused an IndexOutOfBoundsException but because it was not caught the exception is silently dropped and no indication is made that an exception is thrown. For this reason should IndexOutOfBoundsException be a checked exception as it can cause difficult to find bugs ?
Update : the exception is not silently dropped.
Your problem is not Should I catch this exception? it is Why is this exception being consumed unreported?.
There is indeed a fault in the code but the other fault - the hidden one that is quietly consuming your exception and discarding it - is a much more pernicious error.
This is why
...
} catch (Exception e) {
// Ignore it.
}
is almost always a code smell.
No I shouldn't be catched. It's a runtime exception see this link for more details : http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
What you can do is testing on the index you are using against the array length
I would not catch that exception. Instead I would simply check the bounds like this:
if(keyValuesPairs.size() > 0) {...}
You already answered the question:
"I recently tracked down a bug where a list was of length 0 but an access attempt was made at position 1."
It is a bug in the code - you need to resolve the issue where it's even possible for an index larger than array can be used. There's a reason this isn't a checked exception (meaning Java does not require you to catch it). And that reason is you cannot possibly know why an incorrect index was used when the error occurs, and cannot gracefully recover from it.
You should fix the bug you found and not catch the exception. Make it so the exception no longer is thrown.
All RuntimeExceptions are things that ideally, should never need to happen. They are caused when a program is not sufficiently careful with regard to the unknown, and tries to do things that no sane method should ever consider, and with objects and methods they have only the shallowest glimpse of.
Sometimes, a method is unwittingly tricked into attempting something it shouldn't, by a nefarious master who forces them to take a null or empty array, even though the method's documentation indicate it is unqualified to handle such things. But worse still, when the master gets word that their schemes failed, some will try to cover up their failure, by intercepting the exception before it can reach its superiors, corrupting the system with laziness and sloppiness. Even when the master has a suitable way to deal with their failure, they still waste the extra resources and processing power caused by the disorder.
The moral of the story: don't write bad code.
It should not be checked, because if it will be checked then the List interface and others needs to change to add throws to methods that would be overkill.
The exceptions like IndexOutOfBoundsException or NullPointerException should be prevented before they are thrown. These exceptions are RuntimeException that could be occurred when application is run depending on data and not intentionally. The circumstances in which these exceptions occur are unpredictable and cannot say if the code throws exception or not. That's why it should be runtime exceptions.
In you code, to be a valid code, you should check the bounds of index before you use an arbitrary index to access elements of the list. Use isEmpty() or size() to get the condition in which you should correct the flow.

Categories