java exception handling and continuation - java

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
{
...
}

Related

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){}
}
}

Catching an Exception from a called Method

This is something that's been bugging me for a while with regards to Program Flow.
I wanted to know if it's possible to catch an error from a Method in order to stop it from executing the Method that would normally follow it like the example bellow that I can't get to work.
public class MyClass {
public static void main(String[] args) {
// this method catches an exception and stops running
method01();
// this method will continue anyway which I don't want
method02();
};
};
I would normally have a static int variable that will initialize as 0 when the program is run and then if a method ever catches an exception it will increment that int and each method will only run if the int is 0.
This works but I was just wondering if I could replace the int shindig with exception handling.
Can you try:
try {
method01()
} catch (final Exception e) {
// do something
return; ///stop processing exit
}
the method01 will throw Exception:
private void method01() throws Exception {
// something
}
If you only want to terminate the whole program in case of an exception you just need to throw a RuntimeException without any further declaration. There are also specialized sub classes for explicit types of exceptions, like NullPointerException or IllegalStateException. See the "Direct Known Subclasses" section in the JavaDoc.
public class MyClass {
public static void main(String[] args) {
method01();
method02(); //method02 won't be called in case of an exception
}
private static void method01() {
// ...
if (true) // something goes wrong
throw new RuntimeException();
// further code won't be executed in case of an exception
}
private static void method02() {
System.out.println("method02 called");
}
}
Optionally it is possible to handle the exception with a try-catch-block:
public static void main(String[] args) {
try {
method01();
method02(); // method02 won't be called in case of an exception
} catch (Exception e) {
System.err.println("something went wrong");
}
}
// other code keeps unchanged...
If you want to enforce exception handling, you have to throw a subclass of Exception that is not derived from RuntimeException. But those exceptions have to be declared within the method Signature.
private static void method01() throws IOException {
throw new IOException();
}
You put method01 and method02 in to same try block:
public class MyClass {
public static void main(String[] args) {
try {
// This method catches an exception and stops running.
method01();
// This method will not continue if method01 have exception.
method02();
} catch (Exception e) {
e.printStackTrace();
}
}
// declare method01, method02, others...
}
Notice: You have mistakes at the end of code block ( }; }; )
Depends on what your method really does.
If your program should continue working also when an exception arise (e.g. NumberFormatException when parsing an input or in general a checked exception) a lot of people will suggest you to not use exception for flow control, but IMHO in very well defined cases (like NumberFormatException) the flow CAN be controlled by try catch statements and exceptions, it's really up to you.
A way to do so is to use the method returned parameter (also #Nikola answer works in this way, the point is to use the catch part of a try catch as flow control):
public class MyClass {
public static void main(String[] args) {
if(method01()) method02();
};
};
public boolean method01(){
try{
//some business
}catch(MyCheckedException e){
e.printStackTrace();
return false;
}
return true;
}
NB: You should use this approach only in well defined situations! If a file CAN be absent in a directory while opening it (checked FileNotFoundException), you COULD use this approach. If the file SHOULD be there and its not, the exception MUST stop the program.

Disrupting the flow of a program if an error is caught?

Ok I have a method that kicks off an object that deasl with data - a kind of factory.
The factory splits data and sends the data that is split to custom objects that further process/refine the data.
My problem is I log errors with an object that basically just appends the strings together into a log of error. Some errors are ok - meaning the flow of program can continue - however some are serious and therefore the process needs to terminate and I need to throw the error log back to the original method. And stop processing the data at that point or it could mess things up.
The original method returns a string you see. I don't have to worry about how the method returns the error just need to get it to it.
Thanks
It sounds like you should be throwing an exception when you hit a serious error and have the call to the factory within a try catch statement to handle the errors it can generate.
Have a look here http://download.oracle.com/javase/tutorial/essential/exceptions/throwing.html for more information.
The basic code would be
Exception e = new Exception();
throw e;
However you could look at creating your own exception class to contain more information about the specific error caused.
Edit: You mention having an error log to return, a custom exception could have this included within it.
Double Edit:
Somthing like
public class BadFactoryException extends Exception{
private String log;
public BadFactoryException(String log){
this.log = log
}
}
With the factory method that can throw it being something like
public returntype factory throws BadFactoryException(input){
try{
//code goes here
}catch(Exception e){
throw new BadFactoryExeption(log);
}
}
You've just described exceptions and exception handling, a feature of Java since day one.
You don't mention Exceptions in your question - do you use them already?
If not, this is exactly what they are made for.
If you do, then you need to rethink how you are catching the exceptions for your logging.
I'm not a Java person, but I think that you need to use a try {...} catch (error) {...} block. When the desired error is caught, run System.exit(). Here's an example:
try {
/* Do your stuff here */
} catch (ExceptionType name) {
/* Oh noes, a fatal error! */
print('Oh noes!');
System.exit()
}
Is this what you were looking for?
Basic tutorial on exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/
And another good article: http://www.javaworld.com/javaworld/jw-07-1998/jw-07-exceptions.html
If you want to devide critical situations of non critical just do this:
try {
// get here all your work
} catch (TerribleException e) {
// log and exit the application
}
and in your work just don't throw any exceptions. Simple log the situation and continue the work. So all you need is to define what situations should stop the execution, then throw some Exception in that place and catch it in the class which launches the work.
Ok this is what I wanted..finally figured it out.
4 classes including a custom exception.
package ExceptionTest;
public class Main {
public static void main(String[] args) {
exceptionTester();
}
private static void exceptionTester(){
try{
new FirstLevelObj().begin();
}
catch(MyException e){
System.out.println("Its worked!");
e.printStackTrace();
}
finally{
System.out.println("Oh young man..This Class doth created the other classes! \nAnd has now thrown the exception!");
}
}
}
package ExceptionTest;
public class FirstLevelObj {
private SecondLevelObj second;
public FirstLevelObj() throws MyException{
}
protected void begin()throws MyException{
try{
second = new SecondLevelObj();
second.start();
}
catch(MyException e){
throw new MyException("This Is The One!");
}
finally{
System.out.println("And finally..");
}
}
}
package ExceptionTest;
public class SecondLevelObj {
public SecondLevelObj(){
}
protected void start() throws MyException{
for(int i = 0; i<10; i ++){
if(i == 6){
System.out.println("Exception should be thrown:");
throw new MyException("An Error Hath Occurred Young Man!");
}
else{
System.out.println(i);
}
}
}
}
package ExceptionTest;
public class MyException extends Exception{
public MyException(String s){
super(s);
}
}

Categories

Resources