Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize catch block in Java and enable smart insert in Eclipse

In Eclipse when we select code statements and right click on it, it gives us an option for surrounding with try/catch block, after selecting this option our code looks like.

try {
    //selected code lines
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Now I want to define a custom catch block which should look like below after selecting surround with try/catch block from eclipse smart insert:

try {
    //selected code lines
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    myCustomLogger.LogMe(Log.getStackTraceString(e));
}

Is it possible?

Does Eclipse allow us to customize some properties for specific project in smart insert?

like image 545
dd619 Avatar asked May 27 '14 07:05

dd619


People also ask

How do I get the try catch block in eclipse?

In Eclipse, just surround the code you want to enclose with the try-catch block and right-click, then select **Surround with > Try Catch **block. Although you can only have one try statement per try-catch block, you can have multiple catch blocks.

Can catch blocks be polymorphic?

Can catch blocks be polymorphic? I would answer "yes" to this question, because catch blocks can accept not only the exception that they are declared to catch, but also their direct or indirect subclasses. You do not need multiple catch blocks to show polymorphic behavior - a single block would be sufficient.

Can we override catch block in Java?

you basically have two options with Java. You can either swallow the exception, or you can rethrow it. If you swallow it, then the caller of this method won't see an exception. If you rethrow, then the caller would also get an exception.

Can we write method in catch block?

Yes, we can write a return statement of the method in catch and finally block.


1 Answers

Yes it's possible, open Eclipse Preference and then Java > Code Style > Code Templates. There you select Code > Catch block body. Here you can edit your try/catch block.

Add myCustomLogger.LogMe(Log.getStackTraceString(${exception_var}));

enter image description here

like image 195
Paolo Forgia Avatar answered Sep 30 '22 12:09

Paolo Forgia