33 * SPDX-License-Identifier: GPL-2.0-only */
44package de .uka .ilkd .key .java .transformations .pipeline ;
55
6+ import com .github .javaparser .ast .Modifier ;
67import com .github .javaparser .ast .body .TypeDeclaration ;
78import com .github .javaparser .ast .stmt .CatchClause ;
89import com .github .javaparser .ast .stmt .TryStmt ;
2324/// ```java
2425/// try {
2526/// body
26- /// } catch (ExceptionType1 e) {
27+ /// } catch (final ExceptionType1 e) {
2728/// handler
28- /// } catch (ExceptionType2 e) {
29+ /// } catch (final ExceptionType2 e) {
2930/// handler
30- /// } catch (ExceptionType3 e) {
31+ /// } catch (final ExceptionType3 e) {
3132/// handler
3233/// }
3334/// ```
@@ -54,39 +55,33 @@ public void apply(TypeDeclaration<?> td) {
5455 */
5556 private void rewrite (TryStmt tryStmt ) {
5657 var catchClauses = tryStmt .getCatchClauses ();
57-
58- // Process catch clauses in reverse order to safely modify the list while iterating
59- for (int i = catchClauses .size () - 1 ; i >= 0 ; i --) {
60- CatchClause catchClause = catchClauses .get (i );
58+ var originalClauses = catchClauses .stream ().toList ();
59+ for (int i = 0 ; i < originalClauses .size (); i ++) {
60+ CatchClause catchClause = originalClauses .get (i );
6161 var paramType = catchClause .getParameter ().getType ();
62-
63- if ( paramType instanceof UnionType ) {
64- UnionType unionType = ( UnionType ) paramType ;
62+ if ( paramType instanceof UnionType unionType ) {
63+ catchClauses . remove ( i ); // delete original clause
64+ int j = i ;
6565
6666 // Create individual catch clauses for each exception type in the union
6767 for (var elementType : unionType .getElements ()) {
6868 CatchClause newCatchClause = new CatchClause ();
69-
7069 // Create a new parameter with the single exception type
7170 var originalParam = catchClause .getParameter ();
7271 var newParam = new com .github .javaparser .ast .body .Parameter (
7372 elementType .clone (),
7473 originalParam .getName ().clone ());
7574
7675 // Copy modifiers (the parameter is implicitly final in multi-catch)
77- newParam .addFinalModifier ();
78-
76+ newParam .addModifier (Modifier .DefaultKeyword .FINAL );
7977 newCatchClause .setParameter (newParam );
8078
8179 // Clone the body for each catch clause
8280 newCatchClause .setBody (catchClause .getBody ().clone ());
8381
8482 // Insert after the current position (will be before due to reverse iteration)
85- catchClauses .add (i + 1 , newCatchClause );
83+ catchClauses .add (j ++ , newCatchClause );
8684 }
87-
88- // Remove the original multi-catch clause
89- catchClauses .remove (i );
9085 }
9186 }
9287 }
0 commit comments