public class OfficeTimeXception {
public int inTime;
public int outTime;
public void anyXception() throws CoreHourXception, NormalHourException {
int k = outTime - inTime;
if (inTime > 11) {
throw new CoreHourXception(inTime - 11);
}
if (k < 8) {
throw new NormalHourException(8 + (inTime - outTime));
} else if (outTime < 16) {
throw new CoreHourXception(16 - outTime);
}
}
if my try & catch statement is
{test.inTime = 12;
test.outTime = 19;
try {
test.anyXception();
}
catch (CoreHourXception e) {
System.out.println("core hour exception by" + e.getTime()
+ " hours");
e.printStackTrace();
} catch (NormalHourException e) {
System.out.println("normal hour exception by" + e.getTime()
+ " hours");
e.printStackTrace();
}}
I need to catch both exceptions when both conditions fail....but Iam able to get only coreHourException even when both the conditions failed.
You can only throw one Exception at a time, and code execution immediately stops when you do that (the later validations are not run at all).
If you want to check for multiple errors and return all the results at once, you have to collect the validation errors in a Collection and return that Collection (for example by attaching it to a wrapper Exception).
For example
List<Exception> errors = new List<>();
if (errorConditionOne) errors.add(new CoreHourXception());
if (errorConditionTwo) errors.add(new SomeOtherException(123, "abc"));
if (!errors.isEmpty) throw new ValidationException(errors);
These objects that you put in the errors Collection do not have to be Exception objects themselves, they can be anything that you find convenient to convey the information.
Merge CoreHourXception and NormalHourException into an HoreException which reports which conditions are violated:
public class HourException extends Exception {
private boolean normalViolated_;
private boolean coreViolated_;
public HourException(String message, boolean normalViolated, boolean coreViolated) {
super(message);
normalViolated_ = normalViolated;
coreViolated_ = coreViolated;
}
public boolean isCoreViolated() {
return coreViolated_;
}
public boolean isNormalViolated() {
return normalViolated_;
}
}
This is similar to Stephen C's solution. But instead of storing multiple message strings (which cannot be evaluated easily by any exception handler), you explicitly store the information about the violated constraints.
I need to catch both exceptions when both conditions fail....
That is impossible in Java ... and every other programming language I've ever come across.
Basically, only one exception can be thrown and can propagate at a time, and therefore only one exception can be caught.
If you want your code to report all of the failures, then you need to do something like this:
Create an empty list of messages.
Check each condition, one at a time. If the condition "fails", then add an error message to the list.
When you have checked all of the conditions, see if the list is non-empty. If it is, then EITHER convert the list of messages to a string and throw an exception with that string as the message OR throw an exception with a list field, passing the list to the exception via a constructor argument.
You can then catch the exception, and deal with the (possibly) multiple error conditions it is reporting.
Cumbersome? Yes!
Related
I've been trying to find a good solution to this problem for 2 hours, but I haven't found anything useful.
I have method that gets IssueData from mantisApi for use later in the code. It also catches any exceptions thrown:
try {
IssueData issue = mantisApi.getIssue(issueId, user);
task = prepareMantisTask(issue);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return task;
The problem is when I get the IssueData I expect null because it might be an empty field. However when it returns, an exception is caught in this try/catch block. I tried to ignore using the following code:
public String getProjectNotNull(MantisTask mantisTask) {
if (mantisTask == null){
return null;
}
try{
String project = mantisApiCache.getProject(mantisTask.getProject()).getName();
return project;
}
catch(NullPointerException npe){
log.info("TaskService.getProjectNotNull() throws controled null");
return "-";
}
But it looks stupid when I have 20 or more records to check. Is there any other way to ignore nulls? Thank you for your time.
I'm sorry I'm at home now, and i cannot copy code.
prepareMantisTask looks like:
MantisTask mantisTask;
mantistask.setId = issue.getId();
so example. if i do mantistask.setDueData = issue.getDueData(); it is null because not all issues have this parameter. So when the debugger get to this point, it returns to
} catch (Exception e) {
System.out.println(e.getMessage());
}
and left prepareMantisTask with task null.
This two pieces of code are from different parts of my program, I just wanted to show how it works.
Why not just make a null check instead of waiting for an exception?
Perhaps something like this:
public String getProjectNotNull(MantisTask mantisTask) {
if (mantisTask == null){
return null;
}
String project = "-";
// check whatever may be null here
if (mantisTask.getProject() != null
&& mantisApiCache.getProject(mantisTask.getProject()) != null) {
project = mantisApiCache.getProject(mantisTask.getProject()).getName();
} else {
log.info("TaskService.getProjectNotNull() throws controled null")
}
return project;
}
EDIT
In response to your edit, the rule still maintains though. If not all issues have that parameter, you must check it before, so that you never get exceptions because something is null.
Assuming the null pointer exception is due to issue.getDueData(), you likewise do:
if (issue.getData() != null) {
mantistask.setDueData = issue.getDueData()
}
so that you'll never get a null pointer exception in the first case.
In short, there is no way to ignore nulls, you must check each one of them before using them (and never relying on exceptions to check for nulls).
I have the following code:
TestClass test=new TestClass();
test.setSomething1(0); //could, but probably won't throw Exception
test.setSomething2(0); //could, but probably won't throw Exception
I would like to execute: test.setSomething2(0); even if test.setSomething(0) (the line above it) throws an exception. Is there a way to do this OTHER than:
try{
test.setSomething1(0);
}catch(Exception e){
//ignore
}
try{
test.setSomething2(0);
}catch(Exception e){
//ignore
}
I have a lot of test.setSomething's in a row and all of them could throw Exceptions. If they do, I just want to skip that line and move to the next one.
For clarification, I don't care if it throws an Exception, and I can't edit the source code of the code which throws this exception.
THIS IS A CASE WHERE I DON'T CARE ABOUT THE EXCEPTIONS (please don't use universally quantified statements like "you should never ignore Exceptions"). I am setting the values of some Object. When I present the values to a user, I do null checks anyway, so it doesn't actually matter if any of the lines of code execute.
try {
// Your code...
} catch (Exception ignore) { }
Use the word ignore after the Exception keyword.
There is no way to fundamentally ignore a thrown exception. The best that you can do is minimize the boilerplate you need to wrap the exception-throwing code in.
If you are on Java 8, you can use this:
public static void ignoringExc(RunnableExc r) {
try { r.run(); } catch (Exception e) { }
}
#FunctionalInterface public interface RunnableExc { void run() throws Exception; }
Then, and implying static imports, your code becomes
ignoringExc(() -> test.setSomething1(0));
ignoringExc(() -> test.setSomething2(0));
IntelliJ Idea IDE suggests to rename a variable to ignored
when it isn't used.
This is my sample code.
try {
messageText = rs.getString("msg");
errorCode = rs.getInt("error_code");
} catch (SQLException ignored) { }
Unfortunately no, there isn't, and this is by intention. When used correctly, exceptions should not be ignored as they indicate that something didn't work and that you probably shouldn't continue down your normal execution path. Completely ignoring exceptions is an example of the 'Sweep it under the rug' anti-pattern, which is why the language doesn't support doing so easily.
Perhaps you should look at why TestClass.setSomething is throwing exceptions. Is whatever you're trying to 'test' really going to be valid if a bunch of setter methods didn't work correctly?
You can't ignore exception in Java. If a method declares being able to throw something this is because something important can't be done, and the error can't be corrected by the method designer. So if you really wan't to simplify your life encapsulate the method call in some other method like this :
class MyExceptionFreeClass {
public static void setSomething1(TestClass t,int v) {
try {
t.setSomething1(v);
} catch (Exception e) {}
public static void setSomething2(TestClass t,int v) {
try {
t.setSomething2(v);
} catch (Exception e) {}
}
and call it when you need it:
TestClass test=new TestClass();
MyExceptionFreeClass.setSomething1(test,0);
MyExceptionFreeClass.setSomething2(test,0);
You should not ignore Exceptions. You should handle them. If you want to make your test code simple, then add the try-catch block into your functions. The greatest way to ignore exceptions is to prevent them by proper coding.
I know this is old, but I do think there are occasions when you want to ignore an exception. Consider you have a string that contains a delimited set of parts to be parsed. But, this string can sometimes contain say, 6 or 7 or 8 parts. I don't feel that checking the len each time in order to establish an element exists in the array is as straight forward as simply catching the exception and going on. For example, I have a string delimited by '/' character that I want to break apart:
public String processLine(String inLine) {
partsArray = inLine.split("/");
//For brevity, imagine lines here that initialize
//String elems[0-7] = "";
//Now, parts array may contains 6, 7, or 8 elements
//But if less than 8, will throw the exception
try {
elem0 = partsArray[0];
elem1 = partsArray[1];
elem2 = partsArray[2];
elem3 = partsArray[3];
elem4 = partsArray[4];
elem5 = partsArray[5];
elem6 = partsArray[6];
elem7 = partsArray[7];
catch (ArrayIndexOutOfBoundsException ignored) { }
//Just to complete the example, we'll append all the values
//and any values that didn't have parts will still be
//the value we initialized it to, in this case a space.
sb.append(elem0).append(elem1).append(elem2)...append(elem7);
//and return our string of 6, 7, or 8 parts
//And YES, obviously, this is returning pretty much
//the same string, minus the delimiter.
//You would likely do things to those elem values
//and then return the string in a more formatted way.
//But was just to put out an example where
//you really might want to ignore the exception
return sb.toString();
}
Those who write empty catch blocks shall burn in the Hell for the eternity.
Or worse, they will be forced to debug the damn rubbish they wrote forever and ever.
That said, one thing you might want to do is writing exception handling in a less verbose way. The NoException library is very good at that.
in following example, Eclipse does not ask me to add ' throws EmptyStackException'
public E pop() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
...
}
However, in following example, 'throws Exception' is required
public E pop() throws Exception {
if(stack.isEmpty()) {
throw new Exception();
...
}
Is there any specific rules on when should I add throws or not?
This is the difference between checked exceptions and unchecked exceptions.
A checked exception is part of a method signature, and is required to either be caught or declared to be thrown when the method is used. They are subclasses of Exception themselves.
Some examples include a particular constructor of Scanner, or more formally, Scanner#<init>(File file).
Checked exceptions are declared to be thrown typically because it is possible to recover from the exception. For instance, if you were to create a Scanner that read lines from a file, and the file didn't exist, what could you reasonably do besides ask them to re-specify the location?
An example:
Scanner sc = new Scanner(System.in);
boolean found = false;
String path = sc.nextLine();
while(!found) {
try {
sc = new Scanner(new File(path));
found = true;
} catch (FileNotFoundException e) {
System.out.println(path + " was not valid. Please try again.");
path = sc.nextLine();
}
}
An unchecked exception is not part of a method signature, and may be thrown for any particular reason. They are subclasses of RuntimeException.
One of the most common you'll encounter would be NullPointerException. This particular exception could occur in the most innocuous of ways, such as:
Integer i = null;
System.out.println(i + 2); // NPE on unboxing
It is not typically expected for one to be able to recover from the exception; in layman's terms, something has gone wrong with the assumptions made about the flow of code. That is to say, writing this is almost certainly a code smell:
Integer i = null;
try {
System.out.println(i + 2);
} catch(NullPointerException e) {
System.out.println("i was null!?");
}
Most modern frameworks will allow you to specify a specific state that your application enters when such an error occurs - if it's a web driven application, you can have those sorts of runtime exceptions handled as a 500.
There is also Error, which is a special case of unchecked exceptions - you should definitely not recover from this, since it's indicated that something has gone terribly, terribly wrong with the JVM.
For instance, this is something you don't want to see:
public void recurse() {
try {
recurse();
} catch (StackOverflowError e) {
System.out.println("We went in too deep.");
}
}
EmptyStackException extends RuntimeException which is an unchecked exception while Exception is a checked exception.
Java only obliges you to catch checked exceptions. You can read more about this here, here and here.
You don't need to declare/handle RuntimeExceptions in a method signature, but, You have to declare/handle Checked Exception, if the method throws it and not handled inside the method.
In your case, EmptyStackException is a RuntimeException, so, you don't need to handle/declare it in the method, but Exception is a checked one, so, you must need to either handle it or declare it in the method signature
I have a method which returns ArrayList type but I have a try/throw/catch block which does the exception handling. If fail, I would like to return a string saying that it failed.
Example of my code here
public ArrayList<test> testing
{
try
{
Arraylist<test> arr = new ArrayList();
return arr
} catch (exception e) {
return "Failed";
}
}
Above is just example of what I want to do. What is want is when it succeed, it will return the ArrayList which is okay. But when failed, it will return a string. How can I do it? It is possible?
No, your idea seems unsound and in fact impossible since after all, a method can only and should only return one single type. You should consider throwing an exception (my preference), or returning null as a marker (not as good I think since it's less informative).
i.e.,
public ArrayList<test> testing throws SomeException {
Arraylist<test> arr = new ArrayList();
if (somethingFails) {
String message = "an explanation of why the method failed";
throw new SomeException(message);
}
return arr;
}
Instead of trying to return a string in case of an exception, what you should do is throw your own exception type, which would indicate that a failure had occurred (google how to create custom exceptions). Whatever is calling this method needs to be enclosed in its own try-catch block with catch filtering your custom exception first. If that catch block fires, you know a failure has occurred.
I want to catch an exception, that is nested into another exception.
I'm doing it currently this way:
} catch (RemoteAccessException e) {
if (e != null && e.getCause() != null && e.getCause().getCause() != null) {
MyException etrp = (MyException) e.getCause().getCause();
...
} else {
throw new IllegalStateException("Error at calling service 'service'");
}
}
Is there a way to do this more efficient and elegant?
The ExceptionUtils#getRootCause() method can come in very handy in such situations.
There is no more elegant way of selectively "catching" nested exceptions. I suppose if you did this kind of nested exception catching a lot, you could possibly refactor the code into a common utility method. But it still won't be either elegant or efficient.
The elegant solution is to do away with the exception nesting. Either don't chain the exceptions in the first place, or (selectively) unwrap and rethrow the nested exceptions further up the stack.
Exceptions tend to be nested for 3 reasons:
You have decided that the details of the original exception are unlikely to be useful for the application's error recovery ... but you want to preserve them for diagnostic purposes.
You are implementing API methods that don't allow a specific checked exception but your code unavoidably throws that exception. A common workaround is to "smuggle" the checked exception inside an unchecked exception.
You are being lazy and turning a diverse set of unrelated exceptions into a single exception to avoid having lots of checked exceptions in your method signature1.
In the first case, if you now need to discriminate on the wrapped exceptions, then your initial assumptions were incorrect. The best solution is change method signatures so that you can get rid of the nesting.
In the second case, you probably should unwrap the exceptions as soon as control has passed the problematic API method.
In the third case, you should rethink your exception handling strategy; i.e. do it properly2.
1 - Indeed, one of the semi-legitimate reasons for doing this has gone away due to the introduction of the multi-exception catch syntax in Java 7.
2 - Don't change your API methods to throws Exception. That only makes things worse. You now have to either "handle" or propagate Exception each time you call the methods. It is a cancer ...
You should add some checks to see if e.getCause().getCause() is really a MyException. Otherwise this code will throw a ClassCastException. I would probably write this like:
} catch(RemoteAccessException e) {
if(e.getCause() != null && e.getCause().getCause() instanceof MyException) {
MyException ex = (MyException)e.getCause().getCause();
// Do further useful stuff
} else {
throw new IllegalStateException("...");
}
}
I just solved a problem like this by writing a simple utility method, which will check the entire caused-by chain.
/**
* Recursive method to determine whether an Exception passed is, or has a cause, that is a
* subclass or implementation of the Throwable provided.
*
* #param caught The Throwable to check
* #param isOfOrCausedBy The Throwable Class to look for
* #return true if 'caught' is of type 'isOfOrCausedBy' or has a cause that this applies to.
*/
private boolean isCausedBy(Throwable caught, Class<? extends Throwable> isOfOrCausedBy) {
if (caught == null) return false;
else if (isOfOrCausedBy.isAssignableFrom(caught.getClass())) return true;
else return isCausedBy(caught.getCause(), isOfOrCausedBy);
}
When you use it, you would just create a list of if's from most specific Exception to least specific, with a fallback else-clause:
try {
// Code to be executed
} catch (Exception e) {
if (isCausedBy(e, MyException.class)) {
// Handle MyException.class
} else if (isCausedBy(e, AnotherException.class)) {
// Handle AnotherException.class
} else {
throw new IllegalStateException("Error at calling service 'service'");
}
}
Alternative/Addition per requests in comments
If you want to use a similar method to get the Exception object of the class you're looking for, you can use something like this:
private Throwable getCausedByOfType(Throwable caught, Class<? extends Throwable> isOfOrCausedBy) {
if (caught == null) return null;
else if (isOfOrCausedBy.isAssignableFrom(caught.getClass())) return caught;
else return getCausedByOfType(caught.getCause(), isOfOrCausedBy);
}
This could be used in addition to isCausedBy() this way:
if (isCausedBy(e, MyException.class)) {
Throwable causedBy = getCausedByOfType(e, MyException.class);
System.err.println(causedBy.getMessage());
}
It can also used directly instead of isCausedBy(), although it's probably a matter of opinion whether this is more readable.
Throwable causedBy;
if ((causedBy = getCausedByOfType(e, IllegalAccessException.class)) != null) {
System.err.println(causedBy.getMessage());
}
I see no reason why you want exception handling to be efficient and elegant, I settle for effective. They're called Exceptions for a reason.
This code will be a maintenance nightmare. Can't you redesign the call stack to throw the Exception you are interested in? If it is important the method signatures should show it and not hide it wrapped in 2 other exceptions.
The first (e != null) is unnecessary.
And you can change the 3rd better to e.getCause().getCause() instanceof MyException)
You can do as below:
catch (RemoteAccessException e) {
int index = ExceptionUtils.indexOfThrowable(e, MyExcetption.class)
if (index != -1) {
//handleMyException
} else {
}
}
I doubt, but you can check with instanceof if the exception is of the correct type.
Edit: There should be a reason that the nested exception is wrapped, so you have to ask yourself what is the purpose of catching the nested one.
I suppose you could also use ExceptionUtils.throwableOfThrowable() as in here
If you are investigating that whether an exception is caused by a custom exception (e.g. MyException) you can iterate with a while-loop until you find an instance of MyException.
boolean isCausedByMyException(Throwable exception) {
do {
if (exception instanceof MyException) {
return true;
}
exception = exception.getCause();
} while (exception != null);
return false;
}