Proper simple exception handling - java

What should we do in catch block when we can't do anything useful for program work recovery? Say it's simple program, so Logging does not suitable too. For example:
public class Test {
public static void main(String[] args) {
try {
Scanner in = new Scanner(Paths.get("SomeFile.txt"));
//...
} catch (IOException exc){
//System.out.println("Error"); — erroneous, right?
}
}
}

If it's a simple program, either do nothing (don't catch the exception, add throws clause to your main method), or print some error message in the catch block (preferably to System.err). The latter option only makes sense if there is no more code after the catch block (since you don't want to execute any code after the exception is caught).

Related

How to set up a default operation whenever a catch block get executed?

For debugging purposes i want my Java application to upload a log file on my MySql database whenever a catch clause is executed, regardless of which exception is thrown.
The worst solution i thought to was to add my uploader method into each catch in my code (as I already did for the creation of my log file) . This is obviously not elegant method, as long it's repeated code. So my question is: it exist someway (maybe in project proprieties) to set a default operation to be executed whenever a catch clause is met?
There's no way to create a default behavior without typing it into it... Create a global method so you can call it with one line.
One option would be to use a logging framework (no matter if you write this your self or use an existing solution), so you can do:
try{}
catch(Exception e) {Logger.logExceptionToDatabase(e); }
In this you could handle the upload into your database. However I do not thinkt that it is very useful to upload error logs into your database each time a catch block gets executed. I would write them to seperate text logs and collect them and only persist them to a database from time to time or by user request.
To the question itself: This is not possible, however there is a finally block which gets executed after the according try block (as long as the JVM is not terminated within the try block). Maybe you could introduce some TransactionResult and do a logging for each success and failure and than do:
TransactionResult transactionResult;
try{
//do work and at the last line in the try after each operation that could
have failed has been executed set your transactionResult variable
transactionResult = new SuccessTransaction();
}
catch(Excpetion e) { transactionResult= new FailureTransaction();}
finally {Logger.logTransaction(transactionResult); }
and the according classes:
public interface TransactionResult{
public void writeLog();
}
and an example of an transaction result:
public class SuccessTransaction implements TransactionResult{
private String resultStatus;
public SuccessTransaction() { this.resultStatus = "success"; }
public void writeLog() { System.out.println(this.resultStatus); } //or whatever you want to do with your result
}
same goes for your failure instance.
Update
As you stated that there are many Exceptions, you could also pass your Exception to your concrete FailureTransaction and than simply write that message out or collect all the failures in a list and then you can trace which exceptions have been triggered.
You could do something like the following:
public static void myMethod() throws FooException, BarException {
throw new FooException();
}
// if you don't care about specific catch cases:
public static void main(String[] args) throws FooException, BarException {
try {
myMethod();
} catch (Exception x) {
x.printStackTrace(); // default behavior on exception
throw x; // let the specific exception bubble up the call stack
// The compiler knows that this will be either FooException or BarException
}
}
// if you need to also handle specific catch cases:
public static void main(String[] args) throws BarException {
try { // outer try-catch, to handle specific exceptions
try { // inner try-catch to handle default catch behavior
myMethod();
} catch (Exception x) { // Or } catch (FooException | BarException x) {
x.printStackTrace(); // default behavior on exception
throw x; // let the exception bubble up to the specific catch clauses.
// The compiler knows that this will be either FooException or BarException
}
} catch (FooException e) {
System.err.println("Doing something specific to 'FooException'");
// could re-throw if you want to
} catch (BarException e) {
System.err.println("Doing something specific to 'BarException'");
throw e; // only re-throw if you want to
}
}
If you don't need to do anything for specific exceptions then the first main should work just fine.
If you do want to handle specific exceptions on top of your default catch behavior, then just re-throw the exception, catch what it is specifically, and handle that specific case.
You can always re-throw the exception when you want it to bubble further up the call stack.

Java Exceptions check in main()

I have java project contains around 10-15 java files and number of classes. I want to return exit code 1 from catch block inside the main() if any exception occurred any where through out these programs. However all of the classes has exception catch blocks so that exceptions will be handled there itself and catch block inside main() cannot "see" it.
Is there any way to check whether any exception occurred anywhere in the project inside main() of start point without change any code in other files but only at start point.
Thanks
Noushad
You can't. You need to modify the other classes to throw an exception to the caller so that you can catch the exception in main and return the exit code you want.
Write a common "logging" function and call it from any relevant catch block. If you need to exit the program, use System.exit.
public class Defines {
public static LogException(Exception exception) {
...
if (ShouldExitFromException(exception))
System.exit(1);
}
}
elsewhere in your code:
try {
// some code
} catch (Exception exception) {
Defines.LogException(exception);
}
But it will depend what your other catch blocks are actually doing, and to be honest, this all sounds like a bad idea. Logging exceptions might be ok, so you know where and when they're happening, but exiting the program for even ones that have been handled properly is not a good idea.
Throw exception from all methods of all classes and catch it in Main method's catch block. Log exception and then do exit.
public static void main(String[] args)
{
try
{
ClassA.methodX();
ClassB.method();
}
catch(Exception e) //use specific exception class
{
e.printsttrace();
System.exit(1);
}
}
Class A
class classA
{
public static void methodX() throws Exception
{
try{
//perform some operation
}catch(Exception e)
{
//throw exception from here.
}
}

(Java) Try-catching specific lines of code vs Try-catching the whole function

So I'm working on a little project in Java and I've come down to the main method and I'm unsure how I should handle try-catching exceptions correctly.
Should I be:
Try-catching specific lines of code that I know will probably throw an exception?
Like:
public class Stuff {
public static void main(String[] args) {
try {
// code that will probably throw exception 1 or 2
} catch (exception1 e) {
// handle exception 1
} catch (exception2 e) {
// handle exception 2
}
//rest of code that probably won't throw any exceptions
}
}
OR
Try-catching the whole main method even if some of the code in the try block will not throw an exception? Like:
public class Stuff {
public static void main(String[] args) {
try {
// code that will probably throw exception 1 or 2
// rest of code that probably won't throw any exceptions
} catch (exception1 e) {
// handle exception 1
} catch (exception2 e) {
// handle exception 2
}
}
}
One thing to consider is whether or not the code running after the catch block would still be valid if an exception was thrown. For example, consider the following method:
private void readFile()
{
List<String> lines = null;
try
{
lines = Files.readAllLines(Paths.get("/to/my/file.txt"));
}
catch (IOException e)
{
// log exception...
}
for (String line : lines)
{
System.out.println(line);
}
}
If readAllLines throws that IOException, then the code after the catch block will throw a NullPointerException.
There's a bigger question of deciding when to catch vs re-throw an exception. I answer it by asking myself this question:
"Can my method fulfill its contract if this exception is thrown?"
YES: Handle the exception and continue to fulfill the method's contract.
NO: Re-throw the exception (either in throws clause or wrap in a more appropriate exception type).
For example, with this method,
public static List<String> readAllLines(Path path) throws IOException
if the file does not exist, it cannot return a list of the lines of the file, so it throws an IOException.
On the other hand, this method
public static boolean deleteIfExists(Path path) throws IOException
does not throw an exception if the file does not exist (it instead returns the boolean to tell you what happened). One way to think of the contract of this method is, "after this method executes, there will not be a file at path". So in this case, if the file does not exist, the contract is still fulfilled.
That depends - should the non-exceptional code be executed if either exception is raised? This isn't a "best practices" question, this is a "what are your specifications?" question.
Suppose your code looks like this:
String someValue;
try {
someValue = parseSomething();
} catch (ParseFailureException e) {
someValue = defaultValue;
}
// Continue, possibly using the default value
In a case like this, you should wrap only the single line. On the other hand, maybe your code looks like this:
String someValue;
try {
someValue = parseSomething();
} catch (ParseFailureException e) {
log.fatal("The universe is crashing! Run for your lives!");
System.exit();
}
// Continue, assuming that parsing succeeded
In that case, it's a stylistic choice. Either approach is valid, though with such an extreme failure as in this example it might be better to simply declare that the method throws something and forget the try/catch entirely. In fact, whatever your handling code is, if the only thing left for your method to do after it is to bail out, you should consider omitting the try/catch and using a throws clause instead.
This third case, however, is objectively wrong:
String someValue;
try {
someValue = parseSomething();
} catch (ParseFailureException e) {
log.info("something strange happened");
// Don't bother the calling code with the exception, it can't handle it.
}
// Continue, assuming that parsing succeeded
In a case like that, the continuation code must go inside the try block.

How to continue from the starting of code when an exception is thrown?

I’m running a code that throws an exception,I want run the exception code continuously whenever the exception is thrown it has go to starting and should start the program from starting.
Here is my exception method and main
You need to put the try / catch in a loop; e.g. something like this:
public static void main(String[] args) {
while (true) {
try {
// do something
} catch (Exception ex) {
// report ex
}
}
}
Now, the above will repeat the // do something code block until the program is killed, which may not be what you want. If you wanted to terminate when the // do something succeeds, then one solution would be to add a break statement at the end of it. Others could be to set a flag and loop until the flag is set, or even call System.exit(...).
I think I get what you're wanting.
You can explicit throw a generic exception in your try statement which prevents having to generate one through "bad code". You can also pass the "message" you wan to display to this exception and print it out in the catch statement along with the done. Since the exception is handled in the exc() method you won't need the try/catch statement in the main method. It could just be one line.
exc();
public static void exc() {
for(;;){
try{
throw new Exception("Exception");
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Done");
}
}
}
Try this one..
public static void main(String[] args) {
Test_exception_main u = new Test_exception_main();
while(true){
try{
u.exc();
}catch(Exception e){}
}
}

java exception handling and continuation

I have a Java Program where I get data from a different source. some times while reading I see Exception and the program is exiting.
Mine is in a program that runs every 10minutes.
Public static void main(Strings[] args)
{
...readsource();
}
Private static void readsource() throws IOException
{
...
}
Issue:
I am able to get/See the Exception. But I want the program to continue
To that what is the best logic? I dont see try-catch-finally also is not addressing ..I want the program to continue even after seing the exception (I mean the next iteration should continue). This looks to be a Basic issue not sure how to address this...
Then you need to catch the exception, which you are currently not doing.
try {
readsource();
} catch (IOException e) {
// do something, never catch an exception and not do anything
}
//continue.
Note that exceptions usually indicate something is wrong. Unless you are going to do something about the exception, it might be better to fix the condition causing the exception....
You have to provide an error handler in your method, i.e. surround the call to readsource() with a try-catch block.
public static void main(Strings[] args)
{
try{
...readsource();
}
catch(IOException ioe){
//handle the error here,e.g don't do anything or simply log it
}
}
If you don't rethrow the exception in the catch block, execution will fall off the end of the catch block and continue as if there was no exception.
If you mean you'd like to recall the method wether an Exception was thrown or not just place this in a while loop i.e:
Public static void main(Strings[] args)
{
boolean run=true;
while(run) {
try {
System.out.print("Hello,");
readsource();
throw new IOException();
if(1==2)run=false;//stop the loop for whatever condition
} catch(IOException ioe) {
ioe.printStackTrace();
}
System.out.println(" world!");
}
}
}
Private static void readsource() throws IOException
{
...
}

Categories

Resources