Java System setErr() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 1+

Definition

In Java, System.setErr(stream) replaces the standard error stream, the PrintStream behind System.err. Programs use System.err for problems and warnings, and the JVM itself prints uncaught exception stack traces there.

On screen, error text looks like normal output but travels on a separate channel. A shell can send it elsewhere (java App 2> errors.txt); setErr does it from inside the program.

A static method of the java.lang.System class, added in Java 1 (JDK 1.1). Call it on the class name, as in System.setErr(...). No import is needed, because classes in java.lang are always visible.

Syntax

Save the original error stream, redirect it, and restore it in finally:

Java
PrintStream originalErr = System.err;
System.setErr(new PrintStream(errors, true));  // errors is a ByteArrayOutputStream
try {
    // code that may report problems
} finally {
    System.setErr(originalErr);
}
CallWhat it does
System.setErr(new PrintStream(errors, true))Collect error text in memory.
System.setErr(System.out)Merge errors into normal output, keeping the order.
System.setErr(originalErr)Undo the redirect.

Added in Java 1.1. Like System.out, the System.err field is final, so setErr is the only way to change it from code.

Library declarations
Java
// java.lang.System
public static void setErr(PrintStream err)

Parameters

ParameterDescription
errThe new standard error stream.

Return Value

Return ValueDescription
voidNothing; System.err refers to err afterwards.

Compare with Similar Methods

How it relates to the other stream methods:

MethodHow it differs
setOut(stream)Same idea for System.out, the normal output.
setIn(stream)Replaces the input side, System.in.
e.printStackTrace()Writes to System.err, so it follows any setErr redirect.
java App 2> errors.txtShell redirect of the error stream only.

Java Examples

Example 1 — Collect an Error Message Instead of Showing It

A parsing helper reports bad input on System.err. The program captures that message and decides itself how to show it.

Java
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class SystemSetErrCapture {
    static int parseAge(String text) {
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            System.err.println("Bad age: " + text);
            return -1;
        }
    }

    public static void main(String[] args) {
        PrintStream originalErr = System.err;
        ByteArrayOutputStream errors = new ByteArrayOutputStream();
        System.setErr(new PrintStream(errors, true));
        int age;
        try {
            age = parseAge("forty");
        } finally {
            System.setErr(originalErr);
        }
        System.out.println("Result: " + age);
        System.out.println("Error text: " + errors.toString().trim());
    }
}

How It Works

  1. The helper complains. "forty" is not a number, so parseAge catches the NumberFormatException, writes "Bad age: forty" to System.err, and returns -1.
  2. The complaint is caught in memory. During the call, System.err points at errors, so the message lands in the buffer and nothing red appears in the IDE.
  3. Reported on normal output. After finally restores the error stream, main prints the result and the trimmed message through System.out, so both lines appear together.

Example 2 — Merge Errors into Normal Output

Two separate streams can show up out of order or in different places. Pointing System.err at System.out keeps every line in one stream, in the order it was written.

Java
import java.io.PrintStream;

public class SystemSetErrMerge {
    public static void main(String[] args) {
        PrintStream originalErr = System.err;
        System.setErr(System.out);
        boolean merged;
        try {
            System.out.println("1. Starting");
            System.err.println("2. Warning: disk almost full");
            System.out.println("3. Finished");
            merged = System.err == System.out;
        } finally {
            System.setErr(originalErr);
        }
        System.out.println("Merged while running: " + merged);
        System.out.println("Restored afterwards: " + (System.err == originalErr));
    }
}

How It Works

  1. One stream for both. setErr(System.out) passes the output stream itself, so the System.err and System.out fields refer to the very same PrintStream object.
  2. Order is guaranteed. Line 2 is written through System.err but lands in the same stream as lines 1 and 3, so the numbered lines stay in order, even in a redirected file.
  3. Checked with ==. Inside the try, both fields hold the same reference, so merged is true. After finally, System.err is again the saved original, and the last check is true too.

Example 3 — Count Warning Lines Written to System.err

Capture everything a method reports on the error stream, then read the text back line by line and count the warnings.

Java
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringReader;

public class SystemSetErrCount {
    static void process(int[] values) {
        for (int v : values) {
            if (v < 0) {
                System.err.println("WARN negative value " + v);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        PrintStream originalErr = System.err;
        ByteArrayOutputStream log = new ByteArrayOutputStream();
        System.setErr(new PrintStream(log, true));
        try {
            process(new int[] {4, -2, 7, -9, -1});
        } finally {
            System.setErr(originalErr);
        }

        BufferedReader reader = new BufferedReader(new StringReader(log.toString()));
        int warnings = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("WARN")) {
                warnings++;
                System.out.println("Seen: " + line);
            }
        }
        System.out.println("Warnings: " + warnings);
    }
}

How It Works

  1. Warnings for negatives. Of the five values, -2, -9, and -1 are below zero, so process writes three WARN lines to System.err, all collected in log.
  2. Splitting the log into lines. A BufferedReader over a StringReader reads the text back; readLine() accepts both "\n" and "\r\n".
  3. Filter and count. Every line that starts with "WARN" is echoed with a "Seen:" prefix and counted, giving 3 at the end, in the same order the warnings were written.

Frequently Asked Questions

Both are PrintStreams: System.out for normal results, System.err for errors and warnings. Being separate, they can be sent to different places.
Save System.err, call System.setErr(new PrintStream(buffer, true)), run the code, restore the original in finally, and read buffer.toString().
Call System.setErr(System.out). Both fields then refer to the same stream and lines keep their order.
Yes. printStackTrace() and uncaught exception reports write to System.err, so they use the new stream.
Yes, with System.setErr(new PrintStream(new FileOutputStream("errors.log", true))), though a logging framework is usually better.

Next: setIn()

Replace the standard input stream System.in, for example with prepared test input.

setIn() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful