HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaModerate

Retrieving multiple versions of source code for a file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filesourceformultipleversionscoderetrieving

Problem

I have the following code that checks for three different properties. Unfortunately each call can throw up to four exceptions that I all have to catch. Can I some how make the code more readable by reducing the amount of try/catch?

```
public void retrieveSourceCode() {
try {
fileName = RestServices.getInstance().getClassName(getSourceCodeURI());
} catch (ClientProtocolException e) {
fileName = "not available";
e.printStackTrace();
} catch (IOException e) {
fileName = "not available";
e.printStackTrace();
} catch (RestServicesException e) {
fileName = "not available";
e.printStackTrace();
}

if (!(fileName.endsWith(".jar") || fileName.endsWith(".svn-base"))) {
try {
sourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getSourceCodeURI());
} catch (ClientProtocolException e) {
sourceCode = "not available";
e.printStackTrace();
} catch (IOException e) {
sourceCode = "not available";
e.printStackTrace();
} catch (RestServicesException e) {
sourceCode = "not available";
e.printStackTrace();
}

if (before == null) {
beforeSourceCode = "no before source code available";
} else {
try {
beforeSourceCode = RestServices.getInstance().sendGetRequestJsonTextToString(getBeforeVersionURI());
} catch (ClientProtocolException e) {
beforeSourceCode = "no before source code available";
e.printStackTrace();
} catch (IOException e) {
beforeSourceCode = "no before source code available";
e.printStackTrace();
} catch (RestServicesException e) {
befor

Solution

If you upgrade to Java 7, you can use the new Multi-catch syntax. You could change the first block to:

try {
        fileName = RestServices.getInstance().getClassName(getSourceCodeURI()); 
    } catch (ClientProtocolException | IOException | RestServicesException e) {
        fileName = "not available";
        e.printStackTrace();
    }


Essentially if there are many exceptions you catch and handle in the same way, you can use multi-catch

Code Snippets

try {
        fileName = RestServices.getInstance().getClassName(getSourceCodeURI()); 
    } catch (ClientProtocolException | IOException | RestServicesException e) {
        fileName = "not available";
        e.printStackTrace();
    }

Context

StackExchange Code Review Q#7909, answer score: 18

Revisions (0)

No revisions yet.