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

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

Related

Custom exception in java

I have a simple exception and I don't know how to deal with it. My question is what should I do in main?
I know I should create an Exception Class but that's a simple example to understand how should the exceptions be treated in main.
In main I want do display a message and exit the program and I don't understand how to do it.
public void addProfessor() throws Exception {
if(professor) {
throw new Exception(" prof already exists");
}
else {
professor=true;
System.out.println("\n--- addProfessor ---");
System.out.println("Professor: " + professor);
superState=SuperState.OPEN;
System.out.println(superState);
subState=SubState.ASSIGNED;
System.out.println(subState);
}
}
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch(Exception e) {
e.printStackTrace();
}
finally {
}
First of all your example looks like the exception you are trying to use is thrown in standard buisness flow.
It's good practice to keep exceptions to handle really exceptional cases, and not use it in a program flow.
If it's just an example then:
First: (as mentioned in one of comments) better create your own exception (just derive for example from RuntimeException if you want unchecked
or from Exception for checked one) - then you will not catch some other unexpected exception by accident.
Second: when you catch the exception then you have a choice what to do:
do some cleanup & rethrow
just log it
you can also re-try if it makes sense (in your example it does not, because re-trying will just throw another exception - unless the profesor has been removed by another thread)
When you catch the exceptin instead of e.printStackTrace(); you can get a message from the exception or even (as you created your own meaningful exception) you already know the root cause and can just display it to the user.
just an ilustration:
catch(ProfessorAlreadyExistsException e) {
System.out.println("Professor already exists");
}
To create a custom Exception you need to create a class that extends Exception. For example as follow:
public class ProfessorException extends Exception {
public ProfessorException(String msg) {
super(msg);
}
}
Then you need to use this ProfessorException in your code:
public void addProfessor() throws ProfessorException {
if(professor) {
throw new ProfessorException(" prof already exists");
}
...
}
...
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch (ProfessorException e) {
e.printStackTrace();
} finally { // Note that finally block is not needed here because it does nothing
}
If you want to display a message on standard output instead of printing the stack trace you can do that:
try {
C.addProfessor();
C.addProfessor();//here an exception should be displayed because I should have only one professor
} catch (ProfessorException e) {
System.out.println(e.getMessage());
}

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

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.

What is the difference between propagating and handling?

I'm studying for a CS exam this Friday and have hit a bump in the road here. The question asks me to handle the exception and then propagate the exception using two different methods, but I was under the impression they were the same thing. Can anyone help? The practice question is listed below.
You are given the following class:
public class ReadData {
public void getInput() {
getString();
getInt();
}
public void getString() throws StringInputException {
throw new StringInputException();
}
public void getInt() throws IntInputException {
throw new IntInputException();
}
}
class StringInputException extends Exception {}
class IntInputException extends Exception {}
The code above will result in compilation errors in getInput() method.
Rewrite getInput() method using two different techniques:
Method 1 - Handle the exception
Method 2 - Propagate the exception
so that the code compiles.
They are not the same thing. Propagation basically means re-throwing the exception, that is, allowing somewhere further up in the code to handle it; generally this is done if nothing can be done about the exception at the current level. Handling the exception means catching it and actually doing something about it - informing the user, retrying, logging - but not allowing the exception to go any further.
class Example {
// a method that throws an exception
private void doSomething() throws Exception {
throw new Exception();
}
public void testHandling() {
try {
doSomething();
} catch (Exception e) {
// you caught the exception and you're handling it:
System.out.println("A problem occurred."); // <- handling
// if you wouldn't want to handle it, you would throw it again
}
}
public void testPropagation1() throws Exception /* <- propagation */ {
doSomething();
// you're not catching the exception, you're ignoring it and giving it
// further down the chain to someone else who can handle it
}
public void testPropagation2() throws Exception /* <- propagation */ {
try {
doSomething();
} catch (Exception e) {
throw e; // <- propagation
// you are catching the exception, but you're not handling it,
// you're giving it further down the chain to someone else who can
// handle it
}
}
}
"Handle the exception" means to catch it and do whatever is necessary to continue normally.
"Propagate the exception" means to not catch it and let your caller deal with it.
dictionary.com is your friend in this one.
Sometimes we have to deal with that pesky english language.
Handle means do something with the exception,
abort program ,
print error,
mess around with data ...
propagate it means forward it onto someplace else i.e. re throw it.

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