Java Exceptions check in main() - java

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

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.

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

Proper simple exception handling

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

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

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