llvm / llvm/llvm-project

[clang-format] Option to format empty catch clauses on a single line

Open
#184,896 1 comment 0 reactions 0 assignees View on GitHub
clang-format
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

### Problem

With the current clang-format configuration options, it's currently impossible to format a an empty catch clause like this:

```c++
try {
// do stuff
} catch(...) {}
```

### Solution

Adding a new clang-format style option specifically to allow this. Perhaps a boolean would be enough.
`CollapseEmptyCatchClause: true`

### Motivation

Unlike other control statements, catch clauses may serve a useful function while being completely empty. The mere fact of catching the exception and avoiding its propagation, may in certain cases be the most desirable scenario. For instance consider this Java reflection utility

```java
public static T get(Object object, String field, Class type) {
Class t = object.getClass();

while(t != null) {
try {
Field fieldHandle = t.getDeclaredField(field);

if(!fieldHandle.isAccessible())
fieldHandle.setAccessible(true);

return type.cast(fieldHandle.get(object));
} catch(IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch(NoSuchFieldException ignored) {} // desired formatting

t = t.getSuperclass();
}

throw new IllegalArgumentException("Field " + field + " not found for type "
+ object.getClass());
}
```

Other online users have demonstrated a desire for this feature and a workaround is provided in this stackoverflow post: https://stackoverflow.com/questions/59295462/clang-format-catch-with-empty-statement-on-single-line

Personally I'm writing a wrapper around clang-format in bash specifically to deal with this issue: https://github.com/WinterAlexander/winterfmt It will both fix the formatting (when used with -i) and disable warnings related to the format (when used with --dry-run).

I would love to help contributing to fixing this issue. If you are a maintainer, please let me know if I should get started and please feel free to give me any pointers.

Contributor guide

Open the contributing guide

Research direction

The issue proposes a new clang-format option, CollapseEmptyCatchClause, and gives C++ and Java examples of the desired output. Start by tracing how clang-format handles empty catch clauses and its existing formatting-option tests; done means the option produces the requested single-line form without changing other catch formatting.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, java
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.