Manuscript Offprint

arXiv:2609.10397

Retrofitting Code Using LLMs to Support Exceptional Behavior

Linghan Zhong, Jiyang Zhang, Jayanth Srinivasa, Junyi Jessy Li, Milos Gligoric

Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.

Linghan Zhong

The University of Texas at Austin, USA

linghanz@cs.utexas.edu

Jiyang Zhang

The University of Texas at Austin, USA

jiyang.zhang@utexas.edu

Jayanth Srinivasa

Cisco Systems, USA

jasriniv@cisco.com

Junyi Jessy Li

The University of Texas at Austin, USA

jessy@austin.utexas.edu

Milos Gligoric

The University of Texas at Austin, USA

gligoric@utexas.edu

Abstract—Exception Related Code (ERC), which includes throw statements, conditions (if statements) that guard those throw statements, and try/catch blocks, is an essential component of software systems, allowing developers to detect and handle exceptional states that deviate from the expected program behavior. However, manually writing ERC across large codebases is tedious. We propose a novel task: retrofitting existing code with ERC. Namely, given code (without ERC) and Exceptional Behavior Tests (EBTs) (e.g., check if method throws InvalidArgumentException if null is given as the value to the argument) we aim to automatically generate missing ERC, such that the given tests pass. We design and implement Exception Coder (EXCODER) that performs context engineering to help Large Language Models (LLMs) tackle this task. EXCODER integrates static and dynamic program analysis with LLMs by providing the extracted contextual information to the LLMs. To evaluate EXCODER, we build a benchmark constructed from GitHub Java repositories, where we systematically remove ERC in 304 methods from 75 projects. Our results demonstrate that EXCODER provides an effective, though imperfect, solution to this problem in automated code generation, offering developers the first way to implement ERC following test-driven development. When combined with Qwen 2.5 Coder 32b, EXCODER achieves pass@1, 5, and 10 rates of 85.92% (12.56 percentage points over baseline), 86.18% (12.82 p.p. over baseline), and 86.51% (13.15 p.p. over baseline), respectively, on developer-written test suites. Our manual inspection of the generated code further reveals limitations of EXCODER, pointing to directions for future work.

I. INTRODUCTION

Exceptions are supported in many modern programming languages (e.g., C#, Java, Python) and are widely used by developers to indicate that exceptional behaviors, i.e., events outside the expected execution flow of a program, have occurred. Writing exception-related code (ERC), such as throw statements, try/catch blocks, and exceptional condition checks (if statements) that guard the throw statements, is critical for developing reliable software systems, as explicit error signaling prevents hard-to-diagnose failures from occurring further downstream and enables callers to handle exceptions.

Figure 1a shows an example of ERC from a Java project sagiegurari/fax4j. The original implementation allows an AbstractService instance to be initialized multiple times. When reinitialization occurs, important state informa-

public abstract class AbstractService implements Service { public final synchronized void initialize(Map<String, String> configuration) { if (this.initialized) { throw new FaxException("Service is already initialized."); } this.initialized = true; this.serviceConfiguration = new ConfigurationHolderImpl(configuration, this.propertyPart); LoggerManager loggerManager = LoggerManager.getInstance(); this.serviceLogger = loggerManager.getLogger(); this.initializeImpl(); } }

(a) A target method with an exceptional condition check implemented using an if statement to guard the throw statement.

public class AbstractServiceTest { @Before public void setUp() throws Exception { ... this.service.initialize(this.configuration); } @Test(expected = FaxException.class) public void initializeAgainTest() throws Exception { this.service.initialize(this.configuration); } }

(b) An Exceptional Behavior Test (EBT) and its setup.

Fig. 1: A target method and its EBT, from AbstractService in sagiegurari/fax4j.

tion within the object could be reset, potentially causing bugs in downstream operations. To mitigate this issue, developers can add an if statement (line 3) to the target method to check for the exceptional condition and a throw statement (line 4) to signal that an exception has occurred. This approach notifies users of the multiple initialization and halts execution, preventing more complex errors that could arise. Note that exceptional condition checks are not limited to if statements: they can also be written in other forms, such as switch statements whose default case rejects an unsupported value, or try/catch blocks that catch generic exceptions when they occur and throw more descriptive ones.

Despite its importance, writing ERC in appropriate locations is laborious, particularly in large and complex codebases where exceptional behaviors may arise across multiple contexts. To signal exceptions effectively, developers must carefully reason about the specific conditions to decide whether an exceptional behavior has occurred and identify the control flow branches where exceptions need to be signaled.

Large language models (LLMs) have shown remarkable capabilities in code generation and program understanding, making them a promising tool for ERC retrofitting. Prior work on using LLMs to generate ERC [1]–[4] has primarily focused on avoiding unhandled exceptions, which involves automatically detecting locations where exceptions could be thrown and inserting error handling structures to resolve them. However, since they mainly focus on ensuring robust program execution by avoiding exceptions, these approaches are insufficient when developers conversely have specific exceptional behaviors they wish to support with ERC.

Furthermore, unlike these existing approaches that analyze target methods for potentially unhandled exceptions, retrofitting ERC requires knowing the conditions under which developers want exceptions to be thrown. However, formulating the intended exceptional condition checks into natural language prompts can be as laborious for developers as implementing the ERC. A natural solution to this problem is allowing developers to express their intention through concrete test cases, following the principles of Test-Driven Development (TDD) [5]–[7]. TDD, a methodology where automated tests that verify desired functionality are written before the implementation code, is already familiar to many developers. This approach provides an intuitive way for developers to specify exceptional behavior by simply providing example inputs and setups that should trigger exceptions, rather than requiring them to explicitly formulate the exceptional condition checks for when exceptions should be thrown.

In this paper, we propose the novel task of retrofitting existing code with ERC given Exceptional Behavior Tests (EBTs). Figure 1b illustrates an example EBT and its corresponding setup for the target method initialize shown in Figure 1a. In this example, the developer initializes the AbstractService in the setup phase and again within the EBT, then verifies whether a FaxException is thrown.

While our task is based on TDD principles, applying existing TDD-based tools to retrofit ERC presents unique challenges. Much prior work [8]–[11] in TDD has explored applying TDD principles to LLM-based code generation (but not ERC). They often involve a generation and evaluation loop where the model iterates on the previously generated code based on test outputs. However, existing TDD-based methods fail to leverage the rich information contained within EBTs, which includes crucial details such as target exception types and example inputs that trigger exceptional behavior.

To this end, we present Exception Coder (EXCODER), which, given the target method and EBTs, performs context engineering to provide LLMs with useful context for retrofitting ERC. To identify all necessary information for our task, EXCODER employs both static and dynamic pro-

gram analysis. Our static analysis process provides the LLM with contextual information, including available symbols and exception constructors, which supplies the context necessary for implementing syntactically correct throw statements and exceptional condition checks. Dynamic analysis complements this approach by executing the provided EBTs and collecting runtime information, such as reachable code paths. This information from execution gives LLMs insights into how the exceptional condition can be identified and where throw statements can be inserted. We format this contextual information into a prompt. This enables the LLM to generate a new method with ERC incorporated.

To limit the scope of this study, we implement and evaluate EXCODER only for Java projects. We construct a novel benchmark dataset derived from Java repositories collected from GitHub. Our dataset specifically includes target methods that have EBTs covering throw statements in them. For selected target methods, we create “stripped” versions of them that maintain their core functionality but with ERC removed. We then use the corresponding EBTs to evaluate whether ERC added by our framework match the expected exceptional behavior specified in the test suite.

To verify the effectiveness of the context provided by EXCODER, we compare against a baseline prompt that includes only the target method and EBTs, following the literature on TDD [10]. This baseline excludes all context collected by our static and dynamic analysis, which allows us to investigate how the context provided by EXCODER affects the LLM's ability to complete the ERC retrofitting task. Furthermore, to assess the generalizability of our approach across diverse model capabilities, we evaluated EXCODER on 5 distinct models of varying sizes and architectures, including Llama3.1 8b [12], Phi4 14b [13], Qwen 2.5 Coder 7b [14], Qwen 2.5 Coder 32b, and GPT-5 Mini [15]. To evaluate the correctness of the generated ERC, we use pass@k [16] metrics, which estimate the probability that at least one out of k generated samples successfully passes the developer-provided tests. Additionally, to verify that each generated ERC is equivalent to the ground truth, we run automatically generated tests produced by EvoSuite [17] and Randoop [18], and manually inspect the generated code.

The results demonstrate that EXCODER consistently outperforms the baseline across all metrics for the selected models. With Qwen 2.5 Coder 32b, EXCODER achieves gains of 12.56 percentage points on pass@1 (reaching 85.92%), 12.82 p.p. on pass@5 (reaching 86.18%), and 13.15 p.p. on pass@10 (reaching 86.51%) when evaluated on developer-written test suites. Similarly, with GPT-5 Mini, EXCODER achieves gains of 12.30 p.p. on pass@1 (reaching 95.03%), 8.27 p.p. on pass@5 (reaching 97.92%), and 6.91 p.p. on pass@10 (reaching 98.36%). These improvements highlight the effectiveness of EXCODER's context-engineering approach in enabling language models to generate better ERC. Our manual inspection of the generated code further reveals limitations of EXCODER, pointing to directions for future work.

Our work makes the following contributions:

  • We introduce and formalize the problem of retrofitting existing code with ERC given EBTs and code under test.

  • We present EXCODER, which leverages static and dynamic program analysis to perform context engineering, enabling large language models to automatically generate ERC (at appropriate locations in source code).

  • We construct a novel benchmark dataset derived from methods in Java repositories collected from GitHub, specifically methods with existing EBTs for throw statements, which can evaluate generated ERC.

  • We evaluate the effectiveness of EXCODER, and show that it outperforms the baseline by enabling LLMs to generate more methods with ERC that compile and pass tests.

Our code, experimental scripts, and dataset are publicly available at https://github.com/EngineeringSoftware/excoder.

References (39)

  • Towards agentic runtime healing
  • Programming assistant for exception handling with CodeBERT
  • From misuse to mastery: Enhancing code generation with knowledge-driven AI chaining
  • Learning to handle exceptions
  • Impact of test-driven development on productivity, code and tests: A controlled experiment
  • Towards empirical evaluation of test-driven development in a university environment
  • Empirical investigation towards the effectiveness of test first programming
  • AutoCodeRover: Autonomous program improvement
  • Reflexion: language agents with verbal reinforcement learning
  • Test-driven development and LLM-based code generation
  • Competition-level code generation with AlphaCode
  • The Llama 3 Herd of Models
  • Phi-4 Technical Report
  • Qwen2.5-Coder Technical Report
  • Evaluating Large Language Models Trained on Code
  • EvoSuite: automatic test suite generation for object-oriented software
  • Feedback-directed random test generation
  • exLong: Generating exceptional behavior tests with large language models
  • CodeSearchNet challenge: Evaluating the state of semantic code search (opens arXiv in a new tab)
  • How Java programmers test exceptional behavior
  • Learning deep semantics for test completion
  • CAT-LM: Training language models on aligned code and tests
  • ggm1-org/llama.cpp
  • LLMs lean on priors, not programming language semantics
  • Code Llama: Open Foundation Models for Code
  • CodeAgent: Enhancing code generation with tool-integrated agent systems for real-world repo-level coding challenges
  • Is self-repair a silver bullet for code generation?
  • SWE-GPT: A process-centric language model for automated software improvement
  • A survey on software fault localization
  • Fault localization with nearest neighbor queries
  • Visualization of test information to assist fault localization
  • A grouping-based strategy to improve the effectiveness of fault localization techniques
  • Not all exceptions are created equal: Triaging error logs in real-world enterprises
  • CodeRL: Mastering code generation through pretrained models and deep reinforcement learning
  • Which exception shall we throw?
  • Recommending exception handling code
  • CodeBERT: A pre-trained model for programming and natural languages
  • Attention is all you need
  • Language models are few-shot learners