3

We have a package which has many classes and each of them have several methods with try and catch blocks. I need to update the existing code in all the catch blocks of each method.

Do we have any quicker method or way to do the same as the traditional copy paste will take a lot of time?

I tried with find and replace but it does not accept code with a couple of lines.

Manasi k.
  • 43
  • 7
  • Perhaps use a text editor or 'VI' if you are on linux? – J_D Apr 15 '19 at 06:17
  • 2
    Have you seen [that](https://stackoverflow.com/a/50283848/9719337) ? – Dred Apr 15 '19 at 06:18
  • Replacing what with what? Intellij's structural search and replace might help, but obv you are using eclipse, so changing IDE is probably more hassle than you want. – Andy Turner Apr 15 '19 at 06:19
  • 1
    Please add some sample piece of code what you want to modify and mention what modification you need. Do you want to replace the existing catch blocks or want to add some additional piece of code. – Prabir Ghosh Apr 15 '19 at 06:24

2 Answers2

2

You'll need a Regex for replacing couple of lines. Regex will accept code with a couple of lines. Replace all code within catch block with using the Regex.

Eclipse supports regular expressions within the dialog ‘Find/Replace’ (CTRL+F) and from Search->Search(CTRL+H). Don't forget to check the Regular Expression check box.

enter image description here

Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
1

If you really have very many catch clauses, that is a fault you should fix first. Catching an exception should be uncommon, except to do exception translation at the boundary of a subsystem, and at high or medium levels of the program to log useful messages for the system operators. Perhaps you think, or have been told, you must log every exception? That is wrong.

Note that code that does exception translation is easy to change using an IDE, because you can use its refactoring features to quickly change the class name or to add or remove constructor arguments.

If you still have many catch clauses that have the same code (other than simple exception translation), that duplication is the next problem to solve. Extract duplicate code into a shared utility method (or methods). So you can share those methods between classes, they should be static.

Raedwald
  • 46,613
  • 43
  • 151
  • 237