Rishabh Jain
Rishabh Jain

Reputation: 53

Common code for try catch in multiple method in same class of java

I have java class with more than 100 methods and in each method I have to put try catch code. In each try code I have different logic. How can I develop common code in Java?

My sample code:

public void method1(){

    try {
        int a = 2 +3 ;
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public void method2(){

    try {
        int a = 4 +3 ;
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public void method3(){

    try {
        int a = 2 +6 ;
    } catch (Exception e) {
        e.printStackTrace();
    }

}


public void method4(){

    try {
        int a = 2 +9 ;
    } catch (Exception e) {
        e.printStackTrace();
    }

}

There are more than 100+ methods.. and putting try catch in each is hectic.

Kindly advise what I can do.

===========================

My code with consumer::

public class ConsumerCheckExceptionWrapper {

@SuppressWarnings("unchecked")
static <T extends Throwable> T hiddenThrowClause(Throwable t) throws T {
    throw (T)t;
}


public static <T extends Throwable> Consumer<T> tryCatchBlock(ConsumerCheckException<T> consumr) throws T {
    System.out.println("tryCatchBlock method");
    return t -> {
        try {
            consumr.accept(t);
        } catch (Throwable exc) {
            ConsumerCheckExceptionWrapper.<RuntimeException> hiddenThrowClause(exc);
            System.out.println("exc :: " + exc.getStackTrace());
        }
    };
}

}

 @FunctionalInterface 
public interface ConsumerCheckException<T>{
     void accept(T elem) throws Exception; }

// -----------------

// call inside my method:

ConsumerCheckExceptionWrapper.tryCatchBlock(err ->
mymethod(val1,val2));

Upvotes: 1

Views: 2236

Answers (1)

Sanket Patel
Sanket Patel

Reputation: 283

You can add throws declaration in all your method and catch the exception where you call the methods. That will make things simpler. Something like this

public class HelloWorld{

 public static void main(String []args){
    try{
        //call methods here
    }catch(Exception e){
        e.printStackTrace();
    }
 }


 public void method1() throws Exception{

    int a = 4+3;


}

public void method2() throws Exception{

    int a = 4 +3 ;


}

public void method3() throws Exception{

    int a = 2 +6 ;

}


public void method4() throws Exception{

    int a = 2 +9 ;


}

}

Upvotes: 1

Related Questions