Your last solution, to use specific exceptions, would be more readable but could result in a lot of Exception subclass.
Here is a quick code update :
public static void main(String[] args) {
try {
String filePath = getFilePath(args);
AtomicReference<String> content = new AtomicReference<String>();
content.set(readYamlFile(sourceFilePath));
jsonStr = convert(content.toString());
} catch (FileNotFoundException e) {
System.out.println("not found");
} catch (ReadYamlFileException e) {
System.out.println("Not able to load file");
} catch (ConvertJsonExceptione) {
System.out.println("Conversion failed ");
}
}
private String readYamlFile(String) throws ReadYamlFileException{ ... }
private String convert(String) throws ConvertJsonException{ ... }
Since I try to have the return statements in the beginning (filter parameter) or the end of a method (correct method execution), this design is useful.
If not, we would have multiple line that could stop a process, leading to a complicated debugging.
EDIT:
Of course, if you only need to print a text and stop there (no exception management), you can simply create your own exception in each method :
private String readYamlFile(String) throws IOException {
try{
...
} catch (IOException e) {
throw new IOException("Not able to load file", e);
}
}
Where e is the original Exception thrown
Your last solution, to use specific exceptions, would be more readable but could result in a lot of Exception subclass.
Here is a quick code update :
public static void main(String[] args) {
try {
String filePath = getFilePath(args);
AtomicReference<String> content = new AtomicReference<String>();
content.set(readYamlFile(sourceFilePath));
jsonStr = convert(content.toString());
} catch (FileNotFoundException e) {
System.out.println("not found");
} catch (ReadYamlFileException e) {
System.out.println("Not able to load file");
} catch (ConvertJsonExceptione) {
System.out.println("Conversion failed ");
}
}
private String readYamlFile(String) throws ReadYamlFileException{ ... }
private String convert(String) throws ConvertJsonException{ ... }
Since I try to have the return statements in the beginning (filter parameter) or the end of a method (correct method execution), this design is useful.
If not, we would have multiple line that could stop a process, leading to a complicated debugging.
EDIT:
Of course, if you only need to print a text and stop there (no exception management), you can simply create your own exception in each method :
private String readYamlFile(String) throws IOException {
try{
...
} catch (IOException e) {
throw new IOException("Not able to load file", e);
}
}
Where e is the original Exception thrown
I want to stop if exception occurs
You can put return;, System.exit(1), or a throw e; within the catch blocks. Each will halt execution.
Depends on what you want, but you can use just one try block, followed by many catch blocks.
I figured out what and how to do what I was needing. What I needed to stop the creation of the routine object if conditions were met, and that was done by throwing an error. That was being done, but I was mistakenly setting the variables INSIDE the try...catch block. So, if the conditions are not satisfied, it fails and stops, if they are satisfied, it creates the object and sets the variables OUTSIDE of the try...catch block, which works. My new code is as follows:
package routines;
import java.io.IOException;
import java.util.Random;
import game.*;
public class MovePlayer extends Routine {
private final int destX;
private final int destY;
private final Random random = new Random();
public MovePlayer(int destX, int destY, GameBoard board) throws IOException {
super();
try {
if (destY > board.getHeight() || destX > board.getWidth()) {
throw new IllegalArgumentException(">>> Error while creating routine, one or more coords are outside of the game board");
} else {
}
} catch (IllegalArgumentException e) {
fail();
System.err.println(e.getLocalizedMessage());
}
this.destX = destX;
this.destY = destY;
}
By using the
try{
}
catch(Exception){
}
finally{
}
block you can handle exceptions instead of letting them crash your program!
Your code comes in the try block, and in the catch block you can handle the Exception which is being thrown from the executing code in the try-block.
The finally block is used to close or finalize used resources in order to not leave them opened. Not doing that might - ironically - throw you even more exceptions.
I would definitely look up on that, it's a very commonly used part of modern languages!
If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.
Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/
Try this:
try
{
throw new InvalidEmployeeTypeException();
input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
//do error handling
}
continue;
speakToPerson2() is catching the Exception, but you want communicate() to catch it too. Essentially, speakToPerson2() is suppressing the exception, so no other method sees it.
What you need to do is rethrow it (in both speakToPerson2() and speakToPerson3()). This is known as propagating an exception.
I.e.:
public static void speakToPerson2() {
try {
speakToPerson1();
} catch (Exception e) {
System.out.println("speakToPerson2 caused exception");
e.printStackTrace();
throw e;
}
}
public static void speakToPerson3() {
try {
speakToPerson2();
} catch (Exception e) {
System.out.println("speakToPerson3 caused exception");
e.printStackTrace();
throw e;
}
}
You need to understand exactly how try-catch work. If any method in the try-catch throws an exception (one that extends/or is Exception in your example), the body of the try-catch will be interrupted to go into the catch clause.
In your case, the method speakToPerson1 will throw a TryToSpeakException. This exception will be forwarded one step above in the method call stack, the method speakToPerson2 in your case. Since the call to speakToPerson1 is surrounded with a try-catch, the catch clause is invoked and System.out.println("speakToPerson2 caused exception"); is executed. Now, the try clause encloses two methods calls, namely speakToPerson1 and keepSilentToPerson. However, since the first method throw the exception, the second is never reached and therefore keepSilentToPerson() will never by called.
Finally, think about the catching of exceptions. If you catch an exception, you are saying that you are going to handle it, by recovering or rethrowing it. If you handle it without rethrowing it, it won't be forwarded to the upper level of your call stack. Beware of this technicality
Not really sure why you want to terminate the application after the exception is caught - wouldn't it be better to fix whatever went wrong?
In any case, in your catch block:
catch(Exception e) {
e.printStackTrace(); //if you want it.
//You could always just System.out.println("Exception occurred.");
//Though the above is rather unspecific.
System.exit(1);
}
It's true that return would happen to stop the execution of this program (being in main). The more general answer would be if you cannot handle a particular type of exception in a method, you should be either declaring that you throw said exception, or you should wrap your Exception with some kind of RuntimeException and throw that to the higher layer.
System.exit() also technically works, but in the case of a more complex system should likely be avoided (your caller may be able to handle the exception).
tl;dr version:
catch(Exception e)
{
throw new RuntimeException(e);
}