The reliable way to end a Java program when a line of input is invalid is to validate that line first, then terminate deliberately: return from main for silent success, call System.exit(n) for a specific status code, or throw an exception when you want a message and stack trace. For console apps that read line by line, the usual pattern is a validation method that returns a boolean or throws a checked exception, wrapped in a loop or try-with-resources block so you exit without leaking resources. The key condition is separating detecting the bad line from ending the process, because mixing them inside parsing code makes failures hard to test and hard to explain to whoever runs the program.
You also need to decide what "invalid" means before you write any exit logic. A line can be malformed (wrong number of fields), syntactically wrong (a date that isn't a date), semantically out of range (a negative age), or unexpected in context (a command name the parser doesn't recognize). Each category deserves its own validation rule, and often its own exit behavior, since a truly corrupt data file in a batch job is a different problem from a typo by an interactive user who should be allowed to retry.
Decide What Counts as an Invalid Line First
Before adding any exit call, define the contract for a valid line. For a CSV-like input of name,age,city, a valid line has exactly three fields, a non-blank name, an integer age between 0 and 130, and a non-blank city. Write that contract down, then turn it into code that either returns a parsed object or fails with a specific reason. The reason matters because it drives the exit code and message.
A useful split is recoverable versus fatal. Recoverable invalid lines are ones you can skip, log, and move past, such as a stray blank line in an otherwise fine file. Fatal invalid lines are ones that make continuing meaningless, such as a corrupted header or a line that breaks the parser's assumptions about every later line. Ending the program is usually reserved for the fatal case, or for the recoverable case when a flag like --strict is set.
Conflating the two leads to programs that either give up on a single bad row or silently plow through data they shouldn't trust. Sketch the policy in comments or a short design note before coding:
Blank line: skip, count it, continue. Missing field: fail the line, mark file as invalid, continue only in lenient mode. Unparseable number: fail the line with the column name and offending text, then exit if strict. Header mismatch: always fatal.
Validate Before You Branch on It
The most common bug in "end if invalid" code is evaluating the parsed value before checking whether parsing succeeded. Java's Integer.parseInt throws NumberFormatException on bad input; if you catch it but then still reference the returned value, or you check line.length() < 3 only after calling split(","), you get an ArrayIndexOutOfBoundsException instead of your intended clean exit.
Structure the check so the parse and the validation happen once, in one place, and the result is a small value object:
The -1 limit on split keeps trailing empty fields, which makes "missing last column" detectable as a length of 2 rather than being silently swallowed. Using a custom InvalidLineException (unchanged from RuntimeException or extending it) means your caller can catch one type, and your message always names the problem. That single choke point is what makes the exit decision testable: you can unit-test parse without any System.exit anywhere near it.
Use Return From Main When the Exit Is Ordinary
If the program is a small command-line tool and a single invalid line means "nothing to do," returning from main is the least surprising exit. The JVM shuts down with status 0 if main returns normally, and with a nonzero status if an uncaught exception escapes main. So:
Returning is fine, but for automation a plain return still reports success. Callers of your program, including shell scripts and CI pipelines, can't tell a rejection from a clean run unless you use a nonzero status. That's the reason the snippet above calls System.exit(2): status 0 means "valid input handled," status 2 means "rejected input," and the distinction is what lets a script decide whether to retry.
If you truly want silent success on invalid input, return 0 and print the warning to stderr. Print to stderr, not stdout, so pipelines that consume stdout don't get polluted by diagnostics.
Use System.exit for an Explicit Status Code
System.exit(int) asks the JVM to terminate with the given status. It runs shutdown hooks and then stops all threads, including any non-daemon threads you forgot to stop. That last point is its biggest hazard: if you spawn a worker that reads from a socket or a queue, System.exit will kill it mid-operation, possibly after it has written half a file.
For simple programs this trade-off is fine, and System.exit is the correct tool when you need to tell the operating system why you stopped. Use distinct small numbers and document them:
| Code | Meaning | Typical trigger |
|---|---|---|
| 0 | success | all lines valid and processed |
| 1 | general failure | uncaught exception, I/O error |
| 2 | usage error | wrong arguments, missing file path |
| 3 | invalid input, strict mode | first invalid line under --strict |
| 4 | invalid input, lenient mode | at least one invalid line was skipped |
Keep codes stable across releases because scripts depend on them. Reserve 0 and 1 for "worked" and "something unexpected broke," and use the higher numbers for things your program decided on purpose. Avoid returning 128 or above: on Unix-like systems, statuses 129–255 are conventionally used to report "killed by signal," so a program that exits with 137 looks like it was killed with SIGKILL (128 + 9) even though it chose that number itself.
System.exit takes an int, but only the low 8 bits reach the OS on many platforms, so exit(256) shows up as 0. Keep codes under 128 to avoid that surprise.
Throw an Exception When You Want the Full Diagnostic
An uncaught exception that reaches main prints its message and stack trace to stderr and causes the JVM to exit with status 1. For a data pipeline that will be diagnosed by a developer, that's often the most informative outcome: the trace says exactly which method saw the bad line, and the message says what was wrong. If you want a specific status code plus a trace, catch the exception in main, print it, and then call System.exit:
The trade-off is noise. For a command-line tool used by non-developers, a stack trace reads as a crash. Catch the exception, print one clear sentence that names the file, line number, and reason, and exit nonzero. Reserve the trace for a --verbose flag or for exceptions you didn't expect.
Two exception styles work well together. A checked InvalidLineException forces every caller to handle bad input, which suits library code. An unchecked subclass keeps signatures clean, which suits a top-level driver where main is the only caller. Either way, don't use System.exit inside a library method. It makes the library untestable and uncomposable; let the application decide whether an invalid line is fatal.
Close Resources Before You Quit
If you've opened a file, socket, or database connection, close it before exiting. System.exit does not call close() on your objects; it only runs shutdown hooks, and relying on finalizers or try-with-resources nodes that never complete is fragile. The clean pattern is to do all reading inside a try-with-resources so the resource is closed when the block ends, and to decide after the block whether to exit:
Deferring the exit until after the try-with-resources block means the reader is closed and any buffered data is flushed. The alternative, calling System.exit inside the loop, would skip the close unless a shutdown hook handled it, and shutdown hooks that close resources are easy to get wrong. If you have an open network connection or a partially written output file, a shutdown hook that flushes is a reasonable last resort, but a hook that closes a shared resource whose owner is still running can corrupt state. Prefer structured cleanup.
Choose Between Skipping and Stopping
"End the program if invalid" is sometimes the wrong policy. If a 100,000-line data file has two malformed rows, failing the whole job is expensive; skipping the rows, logging them with line numbers, and exiting nonzero at the end preserves the work and signals the problem. That's the "lenient" mode in the table above.
Strict stopping makes sense when each line depends on the previous one, or when bad input means the file was produced by a broken upstream process and anything you do with the rest is untrustworthy. Common examples are a CSV whose header counts fields and whose rows must match, a config file, or a protocol transcript.
A hybrid policy works well: stop on structural failures (unparseable header, wrong field count) and collect semantic failures (out-of-range value, unknown category) for a summary at the end. The program exits nonzero if any failure occurred, but it finishes reading so the operator sees every problem in one run instead of fixing them one at a time.
A Worked Example End to End
Putting the pieces together for a small utility named agesum that reads name,age,city lines and prints the total age:
Prerequisite: Java 17 or later (for record and var), one input file path passed as args, and an optional --strict flag.
1: Parse arguments. If args is empty or the path doesn't exist, print usage to stderr and exit with code 2. 2: Open the file with Files.newBufferedReader inside try-with-resources. 3: Read each line, track the line number, and call parse. 4: On success, add the valid record to a running list and add its age to a total. 5: On InvalidLineException, print path:lineNumber: message to stderr, increment a failure counter, and break out of the loop if strict. 6: After the block, if the failure counter is greater than zero and strict is set, exit with code 3. If not strict but failures occurred, print a one-line summary to stderr and exit with code 4. 7: Print processed N lines, total age T to stdout and let main return for status 0.
Success check: run java agesum data.csv; echo $? (on a Unix shell). Valid data prints the summary and echoes 0. A file with one bad row prints data.csv:4: age is not an integer: 'x' to stderr, and in strict mode echoes 3. In lenient mode it prints the summary plus a warning and echoes 4. If you see echo $? produce 0 after a bad row, your exit happened after a successful return, and you should move the decision out of the catch block.
Common failure modes and their fixes:
Nonexistent file with a stack trace: Files.newBufferedReader throws NoSuchFileException. Catch IOException around the open, print a short message, exit 2. exit code 0 after errors: System.exit was never called, or it was called with 0, or an exception was swallowed in an empty catch block. Add the status decision in one place with no empty catches. Resource ownership errors: The file is still locked after exit, usually because you called exit inside the read loop. Move the call outside the try-with-resources. Invisible to set -e shell scripts: Your program returned 0 on invalid input. Use nonzero exit codes.
Stop condition: if the "invalid line" is actually coming from a network stream, a database result set, or a shared file that another process is concurrently writing, the fix needs coordination with that producer, not just a local exit. Talk to whoever owns that system before changing behavior.
What Not to Do
System.exit inside a finally block silently discards exceptions thrown in the try. If try throws InvalidLineException and finally calls exit(3), the original exception never reaches anyone. Keep exit decisions after the cleanup, not inside it.
Calling System.exit from a catch that is meant to handle a recoverable case turns a warning into a shutdown and hides later problems. Separate the "log this and continue" path from the "stop now" path in code, so the intent is visible.
Assuming System.exit happens instantly is also wrong. It triggers shutdown hooks and then ends the JVM; if a hook hangs, the process hangs. If you add a hook, keep it fast and free of blocking I/O.
Finally, printing "invalid input" and returning 0 is the most common cause of silent failures in build pipelines. If your program's job is to reject bad data, its exit status must say so. Anyone calling it from a shell or CI system will thank you for a stable, documented nonzero code.
General note: This is programming guidance, not legal or compliance advice. Exit codes and data-handling requirements can matter in regulated systems, so confirm specific requirements with whoever owns that system.