surround "throw new Exception()" with try catch - java

throw new Exception();
If you put this statement in a method, you should either add throws Exception after the method name. Or, you can surround the statement with try-catch.
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But what is it the point here? The compiler permit it, so I just want to know if it is designed intentionally. I am curious.

Actually, this is useful in some scenarios.
Say, you want to perform a series of tasks and if any one of them fails, you want to abort the sequence and do some other task.
It is true that you can do the same with a series of if statements, but this provides another way to do it.
try{
// do task 1
// if failed, throw new Exception("Task 1 Failed");
// do task 2
// if failed, throw new Exception("Task 2 Failed");
// do task 3
// if failed, throw new Exception("Task 3 Failed");
...
}catch(Exception e){
// System.err.println(e.getMessage());
// do somthing else
}

Related

executor.invokeAll() lambda body does not return

The idea is for some kind of compiler, and I'm trying to implement a fork statement that starts another thread.
The code:
List < Callable < CustomClass >> callList = lista.stream().map(p -> (Callable < CustomClass > )() -> p.oneStep()).collect(Collectors.toList()); //here I just prepared the list of callables
List < CustomClass > newPrgs;
try {
newPrgs = executor.invokeAll(callList).stream().map(future -> {
try {
return future.get();
} catch (Exception e) {
e.printStackTrace();
}
}
/here it indicates the error/.filter(p -> p != null).collect(Collectors.toList());
} catch (InterruptedException e) {
throw new CustomException(e.getMessage());
}
The error is: lambda body is neither value nor void compatible. I tried all sort of changes and tricks, and no result. Some help please?
The problem is in the definition of your lambda...
{
try{
return future.get();
}
catch (Exception e){
e.printStackTrace();
}
}
Now, this is fine for the happy path, which just returns the response from the future, but in the event of an exception this lambda will not return a value. You need to return something from the exception case, or throw a RuntimeException. Which to do depends on your use case - an exception will stop the entire stream from processing, but a null or default value could risk polluting your stream.
Also, it's generally best not to catch Exception - keep the catch down to the minimal set necessary / that you can handle.
The exception-throwing form would look like...
{
try{
return future.get();
}
catch (InterruptedException | ExecutionException e){
e.printStackTrace();
throw new RuntimeException(e)
}
}
Take a look at your lambda's body:
try {
return future.get(); // This branch returns a value
} catch (Exception e) {
e.printStackTrace(); // No return statement here
}
// No return statement here either
So your lambda can neither be translated into a void method, not into a method with a return value.
You should have a return value either at the catch or at the end of the lambda body.

Java: try/catch with InputMismatchException creates infinite loop while reading of a file

I have a task to make a program that will add up all the valid integers in a file and to ignore anything that isn’t a valid int. I have to use Try and Catch.
File Numbers = new File("Numbers.txt");
Scanner readFile = null;
int i = 0;
int total= 0;
boolean success = false;
while(!success){
try {
readFile = new Scanner(Numbers);
while(readFile.hasNext()){
i = readFile.nextInt();
System.out.println(i);
total = i + total;
};
success = true;// Ends The loop
} catch (FileNotFoundException e1) {
System.err.println(Numbers.getName()+" does not exist");
}
catch(InputMismatchException e2){
System.err.println("Data incorrect type expecting an int found: " + readFile.nextLine());
readFile.next();
}
System.out.println("total is: " + total);
};
The problem is that the program gets caught in an infinite loop, where instead of going past the exception it just starts again.The task seems pretty straight forward, yet i don't know why it wont work?
You fall into infinite loop because when exception happens, the success variable didn't change its value to true. In order to do some action even when exception happens you should add the finnaly block. It could look like this:
try {
// do some stuff
} catch (Exception e) {
// catch the exception
} finally {
if (!readFile.hasNext()) success = true;
}
And by the way, never do this: catch (Exception e), I did it just for example sake. Instead always catch the specific exception. Because Exception is the most basic class in the exception hierarchy, so it will catch up all the exceptions, and unless you re-throw it you could have false feeling of "safiness". When you want to catch all the exceptions, you should do this:
try {
// do stuff
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
e.printStackTrace(); // or other approptiate action, i.e. log it.
}
Assume any of the following FileNotFound or InputMismatchException exceptions will raise, then your program wont change success to true. Thus it returns to the outer while loop and read the same file. Because nothing has changed the same Exception will be thrown again.
==> Endless loop.
To fix that I suggest to move the try/catch block to the inner while.

Why such output is coming?

It might be easy but I don't understand why the output is coming as 1 4. And what is the function of the return statement at Line 9?
public static void main(String[] args) {
try{
f();
} catch(InterruptedException e){
System.out.println("1");
throw new RuntimeException();
} catch(RuntimeException e){
System.out.println("2");
return; \\ Line 9
} catch(Exception e){
System.out.println("3");
} finally{
System.out.println("4");
}
System.out.println("5");
}
static void f() throws InterruptedException{
throw new InterruptedException("Interrupted");
}
Thanks in advance.
Your function f() throws InterruptedException, which is caught by the first catch block (hence it prints 1), but this catch block cannot throw other exceptions (if it is not thrown by your method), Hence, no other catch block can catch your excception and therefore finally is executed (finally executes in every case except those silly infinite loop cases). you can refer to Exception thrown inside catch block - will it be caught again?.
I hope it helps.
Just to summarize, you can throw any exception from try block & it will be caught (if there is a good catch block). But from catch block only those exceptions can be thrown (and consequently caught by) which your method throws.
If you throw exception from catch block which are not thrown by your method, it is meaning less and won't be caught (like in your case).
As you can see f() throws InterruptedException, so it will first print 1 which is inside first catch block and then finally would execute so it will print 4.
The 1 is printed because f() throws an InterruptedException. Because the Exception is handled in the first catch block it is not handled in the other exception blocks belower anymore. The finally statement is always run, so the 4 is printed too.
try{
f();
} catch(InterruptedException e){
System.out.println("1");
throw new RuntimeException(); // this RuntimeException will not catch by
//following catch block
} catch(RuntimeException e){
You needs to change your code as follows to catch it.
try{
f();
} catch(InterruptedException e){
System.out.println("1");
try {
throw new RuntimeException();// this RuntimeException will catch
// by the following catch
}catch (RuntimeException e1){
System.out.println("hello");
}
} catch(RuntimeException e){
System.out.println("2");
return;
} catch(Exception e){
System.out.println("3");
} finally{
System.out.println("4");
}
System.out.println("5");
Then your out put"
1
hello // caught the RunTimeException
4 // will give you 2,but also going to finally block then top element of stack is 4
5 // last print element out side try-catch-finally
f() throws an InterruptedException so you get the 1. finally is always called at the end so you get the 4.
As f() throw InterruptedException which executes,
catch(InterruptedException e){
System.out.println("1");
throw new RuntimeException();
}
prints --> 1
and finally gets executed before exiting the program,
finally{
System.out.println("4");
}
prints --> 4
Code after return wont execute but finally will get executed.

Is it safe to use multiple startTransaction and commitTransaction with just one last endTransaction in iBatis?

I wrote a program to insert bulk data. To speed up, I committed transaction in the middle of process.
Is it safe to call startTransaction and commitTransaction many times and call endTransaction just once?
try {
sqlMap.startTransaction();
// Do some work.
sqlMap.commitTransaction();
sqlMap.startTransaction();
// Do some work.
sqlMap.commitTransaction();
sqlMap.startTransaction();
// Do some work.
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
throw new MyException();
} finally {
try {
sqlMap.endTransaction();
}
catch (SQLException e) {
e.printStackTrace();
throw new MyException();
}
}
Thanks.
In iBatis, startTransaction, commitTransaction, endTransaction should be called one time in order as stated. If you call startTransaction and commitTransaction many times without calling endTransaction, you will run out of db connection and get errors.

Java 1.6 : Learn how to handle exceptions

I did extensive research on exceptions, but I'm still lost.
I'd like to know what is good to do or not.
And I'd also like you to give me your expert opinion on the following example :
public void myprocess(...) {
boolean error = false;
try {
// Step 1
try {
startProcess();
} catch (IOException e) {
log.error("step1", e);
throw new MyProcessException("Step1", e);
}
// Step 2
try {
...
} catch (IOException e) {
log.error("step2", e);
throw new MyProcessException("Step2", e);
} catch (DataAccessException e) {
log.error("step2", e);
throw new MyProcessException("Step2", e);
}
// Step 3
try {
...
} catch (IOException e) {
log.error("step3", e);
throw new MyProcessException("Step3", e);
} catch (ClassNotFoundException e) {
log.error("step3", e);
throw new MyProcessException("Step3", e);
}
// etc.
} catch (MyProcessException mpe) {
error = true;
} finally {
finalizeProcess(error);
if (!error) {
log.info("OK");
} else {
log.info("NOK");
}
}
}
Is it ok to throw a personnal exception (MyProcessException) in each step in order to manage a global try...catch...finally ?
Is it ok to manage each known exception for each step ?
Thank you for your help.
EDIT 1 :
Is it a good practice like this ? log directly in global catch by getting message, and try...catch(Exception) in upper level....
The purpose is to stop if a step fail, and to finalize the process (error or not).
In Controller
public void callProcess() {
try {
myprocess(...);
} catch (Exception e) {
log.error("Unknown error", e);
}
}
In Service
public void myprocess(...) {
boolean error = false;
try {
// Step 1
try {
startProcess();
log.info("ok");
} catch (IOException e) {
throw new MyProcessException("Step1", e);
}
// Step 2
try {
...
} catch (IOException e) {
throw new MyProcessException("Step2", e);
} catch (DataAccessException e) {
throw new MyProcessException("Step2", e);
}
// Step 3
try {
...
} catch (IOException e) {
throw new MyProcessException("Step3", e);
} catch (ClassNotFoundException e) {
throw new MyProcessException("Step3", e);
}
// etc.
} catch (MyProcessException mpe) {
error = true;
log.error(mpe.getMessage(), mpe);
} finally {
finalizeProcess(error);
if (!error) {
log.info("OK");
} else {
log.info("NOK");
}
}
}
Thank you.
Edit 2 :
Is it a real bad practice to catch (Exception e) in lower level and to throws a personnal exception ?
Doesn't exist a generic rule,it depends on your needs.
You can throw a personal exception, and you can manage each known exception.
But pay attention, it is important what you want.
try{
exec1();
exec2(); // if exec1 fails, it is not executed
}catch(){}
try{
exec1();
}catch(){}
try{
exec2(); // if exec1 fails, it is executed
}catch(){}
In your example above it may well be acceptable to throw your own custom exception.
Imagine I have some data access objects (DAO) which come in different flavours (SQL, reading/writing to files etc.). I don't want each DAO to throw exceptions specific to their storage mechansim (SQL-related exceptions etc.). I want them to throw a CouldNotStoreException since that's the level of abstraction that the client is working at. Throwing a SQL-related or a File-related exception would expose the internal workings, and the client isn't particular interested in that. They just want to know if the read/write operation worked.
You can create your custom exception using the originating exception as a cause. That way you don't lose the original info surrounding your problem.
In the above I probably wouldn't handle each exception in each step as you've done. If processing can't continue after an exception I would simply wrap the whole code block in an exception handling block. It improves readability and you don't have to catch an exception and then (later on) check the processing status to see if you can carry on as normal (if you don't do this you're going to generate many exceptions for one original issue and that's not helpful).
I would consider whether multiple catch {} blocks per exception add anything (are you doing something different for each one?). Note that Java 7 allows you to handle multiple exception classes in one catch{} (I realise you're on Java 6 but I note this for completeness).
Finally perhaps you want to think about checked vs unchecked exceptions.
The main point of the exception mechanism is to reduce and group together handling code. You are handling them in the style typical for a language without excptions, like C: every occurrence has a separate handling block.
In most cases the best option is to surround the entire method code with a catch-all:
try {
.... method code ...
}
catch (RuntimeException e) { throw e; }
catch (Exception e) { throw new RuntimeException(e); }
The only times where this is not appropriate is where you want to insert specific handling code, or wrap in a custom exception that will be specifically handled later.
Most exceptions, especially IOExcption in your case, represent nothing else but failure and there will be no handling beyond logging it and returning the application to a safe point, where it can process further requests. If you find yourself repeating the same handling code over and over, it's a signal that you are doing it wrong.
One very important rule: either handle or rethrow; never do both. That is what you are doing in your example: both logging and rethrowing. Most likely the rethrown exception will be caught further up in the call stack and logged again. Reading through the resulting log files is a nightmare, but unfortunately quite a familiar one.
int step = 0;
try
{
step = 1;
...
step = 2;
...
step = 3;
...
}
catch (Exception1 e)
{
log ("Exception1 at step " + step);
throw new MyException1 ("Step: " + step, e);
}
catch (Exception2 e)
{
log ("Exception2 at step " + step);
throw new MyException2 ("Step: " + step, e);
}
...
I'd say it depends on your needs...
If step2 can execute correctly even if step1 failed, you can try/catch step1 separately.
Otherwise, I would group all steps in one try/catch block and made sure that the individual steps produce a log message when they fail.
That way you don't litter your code and still know what went wrong
It's ok to catch each known exception, so you can log what exception occure, and why it did.
Here some links to exception handling patterns/anti-patterns:
Do:
http://www.javaworld.com/jw-07-1998/jw-07-techniques.html
Don't:
http://today.java.net/article/2006/04/04/exception-handling-antipatterns
http://nekulturniy.com/Writings/RebelWithoutAClause/Rebel_without_a_clause.html
About creating your own exceptions, it's certainly useful if you're creating an API, a framework or another piece of reusable code, but in a regular application, it's more debatable and I personally would suggest to stick to existing exceptions.

Categories

Resources