Exceptions .. redirecting System.err

I've redirected System.err to a custom class that extends OutputStream.
I have a couple of questions which someone in here might know the answer to:
1. When I receive an exception write(byte b[], int off, int len) is called. The array of bytes is always 8192 long - padded with \x0000 at the end. Why?
2. How do I know an exception has ended? I want to notify the user when it has ended (with a popup). But write() is called for each line, and flush() doesn't seem to be called at all.
Best regards,
Bjorn

Depends what kind of a program you are writing. If you are doing a standalone application, you can always have a master try-catch block in the main() method that will catch Throwable. Nothing should make it past that.
Now, if you are doing a servlet or EJB, you don't want to trap every exception because the container is supposed to receive and handle them for you (thread death, out of memory, etc.) If you have a front-controller pattern implemented, you can put a master try-catch block there and do something like the following:
try {
// implement cool functionality here
catch (RuntimeException e) {
// use code to retrieve stack trace
throw e;
catch (Exception e) {
// use code to retrieve stack trace
// handle exception in application-specific manner
catch (Error e) {
// use code to retrieve stack trace
throw e;
The cool "feature" about exceptions is that they propogate. So, if you don't have the appropriate catch block, it will move to the previous caller. Hence, you can have a master exception processor if either a) you re-throw exceptions on to be procsesed by the master exception processor or b) you don't handle the exception at all and let it propogate naturally.
You also have a number of options so you don't have to rewrite 300 exception try-catch blocks. Subclass Exception, and for all your custom exceptions, put the functionality to dump or store the stack trace there. It will happen anytime your custom exception is instantiated.
Lots of ways to skin a digital cat. However, the argument that you will have to change code to get new functionality is part and parcel of the beast. If you want to capture the stack trace and do something with it, code somewhere will have to change. Either use inheritance, delegation or the exception propogation mechanism inherent to Java to minimize your work.
- Saish
"My karma ran over your dogma." - Anon

Similar Messages

  • Redirecting System.err on a mobile phone?

    Hi,
    Is there a way of redirecting System.err? Unfortunately, System.setErr does not exist in MIDP, so I haven't been able to write my own PrintStream to replace err.
    I need to know what the output of Exception.printStackTrace() is at a certain point. There is certainly a way of accessing System.err, otherwise it wouldn't be present in MIDP ... .
    Thanks!
    Stefan

    Hi
    J2ME Polish provides a logging framework, which offers different logging levels and the ability to view logging messages on real devices.
    Mihai

  • How redirect System.err ?

    Hi,
    I'm debbuging on device and I would like to change the System.err value to redirect its outputs.
    I have some log methods to write common outputs in a text file on the device, and I need to check the output of the mehtod Exception.printStackTrace().
    How can I redirect System.err ??
    Thanks in advance,

    Well, as a matter of fact, CLDC/MIDP specifications (this is CLDC and MIDP forum JFYI) do not provide means for application to get printStackTrace output anyhere else but System.err.
    You can not change that fact, no matter how you try. Oh and this is a verifiable fact - anyone can get mentioned specifications and check if it's true.
    I would also add that per my reading of above specifications, compliant device even "has a right" to simply swallow anything that goes to System.err - including the output of printStackTrace.
    I mean, specs allow devices where trying to get output of printStackTrace is the same as trying to get something from [ /dev/null|http://en.wikipedia.org/wiki//dev/null]. Oh and by the way my conclusion is, again, verifiable - that is, anyone can get the specs and check if there's a requirement for devices not to behave that way.
    Does that answer your question?

  • How do I redirect System.err output in iPlanet 4.1?

    All,
    I've been trying for days to redirect System.err output from a Java program
    to a log file. I followed the instructions here:
    http://knowledgebase.iplanet.com/ikb/kb/articles/4790.html
    Unfortunately, nothing has been written to any of the log files (even though
    I have plenty of System.err.println()'s in my code).
    Anyone else get this to work correctly?
    Thanks in advance,
    --Bill                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi,
    What is the product web server or application server ? If it is application
    server then I'm very sure that this output will be seen in the kjs log file in
    Unix and in the command window in Windows NT/2K, only if you have allowed the
    process to interact with desktop. Please let me know if this answers your
    question for me to help you further on this.
    Regards
    Raj
    "news.uswest.net" wrote:
    All,
    I've been trying for days to redirect System.err output from a Java program
    to a log file. I followed the instructions here:
    http://knowledgebase.iplanet.com/ikb/kb/articles/4790.html
    Unfortunately, nothing has been written to any of the log files (even though
    I have plenty of System.err.println()'s in my code).
    Anyone else get this to work correctly?
    Thanks in advance,
    --Bill                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Redirecting System.err to a JOptionPane

    Hello,
    I tried to write a piece of code which shows all exceptions in a JOptionPane instead of the console. But I meet two difficulties:
    1. I don't know how to detect the line count of the error message (so that currently I have to display the optionPane for each error line, which is unacceptable).
    2. I receive more error messages than expected. The produced parse error gives 5 lines on a console, but here I receive 60.
    What's wrong?
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    class Redirecting extends JFrame {
      public Redirecting() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300,300);
        JTextAreaOutputStream err= new JTextAreaOutputStream();
        System.setErr(new PrintStream(err));
        JButton b= new JButton("Produce error");
        b.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
         System.out.println(Integer.parseInt("1"));
         System.out.println(Integer.parseInt("2"));
         System.out.println(Integer.parseInt("Error"));
        add(b, BorderLayout.SOUTH);
        setVisible(true);
      public static void main(String[] args) throws Exception {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
         new Redirecting();
      class JTextAreaOutputStream extends OutputStream {
        int icnt=0;
        private JTextArea area;
        public JTextAreaOutputStream() {
          area= new JTextArea();
        public void flush() throws IOException {
          JOptionPane.showMessageDialog(Redirecting.this, area, "Error",
                                  JOptionPane.ERROR_MESSAGE);
    //      area.setText("");
        public void write(byte b[]) throws IOException {
          area.append(new String(b));
        public void write(byte b[], int off, int len) throws IOException {
          System.out.println(icnt++);
          String s = new String(b , off , len);
          area.append(s);
          flush(); // to make error lines visible
        public void write(int b) throws IOException {
          area.append(String.valueOf(b));
    }

    maybe this ?
          * recieving error for testing
          * @param e
         protected void bt_generateError_actionPerformed(ActionEvent e) {
              DateFormat fo = new SimpleDateFormat("mm.dd.yyyy");
              try {
                   // Here reciev parsing error
                   fo.parse("sacascsa");
              } catch (ParseException e1) {
                   String exception = Util.formateException(e1.getStackTrace());
                   // show error
                   Util.showException(frame, exception);
          * utilita
          * @author Dima
         public static class Util {
               * formateException formating error in way you want
               * @param stack
               * @return
              public static String formateException(StackTraceElement[] stack) {
                   String formatedException = "";
                   for (int i = 0; i < stack.length; i++) {
                        System.err.println(stack.getClassName() + ""
                                  + stack[i].getMethodName() + "" + stack[i].getClass()
                                  + " Line" + stack[i].getLineNumber());
                        formatedException = formatedException.concat(
                                  stack[i].getClassName()
                                  + "."
                                  + stack[i].getMethodName()
                                  + " "
                                  + stack[i].getClass()
                                  /** + " Line" + stack[i].getLineNumber() */
                                  + "\n"); // remove comment and recieve errors line
                                                 // numbers
                   return formatedException;
              * showException return JOptionPane with formatted error
              * @param com
              * @param exceptionText
              public static void showException(Component com, String exceptionText) {
                   JPanel canva = new JPanel();
                   canva.setMinimumSize(new Dimension(300, 200));
                   canva.setPreferredSize(new Dimension(300, 200));
                   JTextArea area = new JTextArea();
                   area.setText(exceptionText);
                   JScrollPane pan = new JScrollPane();
                   pan.getViewport().setView(area);
                   canva.setLayout(new BorderLayout());
                   canva.add(pan);
                   JOptionPane.showMessageDialog(com, canva, "Error Title",
                             JOptionPane.ERROR_MESSAGE);

  • Redirecting System.err to a TextArea

    Hi there !
    I want to redirect the output of System.err to a TextArea.
    System.err is everywhere in my project. Is there any simple way to just redirect the output of this err to some TextArea?
    Thanks in Advance
    Dexter

    See the API java.lang.System.setErr()You will then need to start a thread to read from the PrintStream and put the
    output in your text area.
    - ajay

  • How do I redirect System.err msg on NT

    As you probably already know, when running a standard alone java program, say myapp.class, if one wants to redirect the System.out.println message, one might do this on NT dos prompt:
    java myapp > myout.txt
    In this case, all messages from System.out.println that suppose to print on the screen are redirected to be written into myout.txt.
    If your error messages are displayed using System.err.println, the same command does not save your message to the file redirected as above. Does anyone know how can I do some similar thing in the command line to redirect my error messages into a file?
    Thanks for help.
    Stan

    to redirect standard error on nt:
    java myapp 2> myout.txt

  • System.out vs System.err questions

    Hello,
    System.out and System.err both seem to direct regular and error output to the stdout. I have the following questions:
    1. I used System.setOut() to direct regular output to "Output.txt" and System.setErr() to direct errors to "Errors.txt". I purposely made the program to throw some exceptions, wanting to redirect them to "Errors.txt". It did not work. My question is "What kind of errors setErr() would direct to an error file?"
    2. Without using setErr(), errors go to stdout. My question is "Does Java hava a configuration file I can configue to direct regular output to stdout, but errors to a user-defined file such as errors.log?"
    Thanks!

    I see the stack trace in file err.txt:
    import java.io.*;
    public class Example {
        public static void main(String[] args) throws FileNotFoundException {
            System.setOut(new PrintStream(new FileOutputStream("out.txt"), true));
            System.setErr(new PrintStream(new FileOutputStream("err.txt"), true));
            System.out.println("<stdout>");
            System.err.println("<stderr>");
            throw new RuntimeException("here we go");
    }

  • How does javaw (WinXP) threats System.err and System.out?

    Hi, I just faced a problem which is most likely caused by the blocking of System.err.
    So I'm interested in the default handling of theses streams by javaw.
    I would except that they point to something like "/dev/null" (compared to Unix), but the behavior is different.
    I'm sure about this, cause redirecting these streams had fixed my problem.
    (see http://forum.java.sun.com/thread.jspa?messageID=9516593)
    Thanks a lot in advance.
    Greetings Michael
    The entry from the registry:
    "C:\Programme\Java\jre1.6.0\bin\javaw.exe" -jar "%1" %*"

    Bumping.

  • [Feature Request] Seperate tab in log window for System.err

    By default, the stack traces of exceptions (and throwables in general) are printed to the System.err stream. So, wouldn't it be useful to include a 2nd tab for System.err messages?
    It could be optional to either include or leave out the System.err output in the System.out tab.
    The whole idea of this 2nd tab is to set it up like the search output tab: a tree-like list which can be expanded to see the stack trace of each exception that occured during runtime. A small parser can parse the stack trace when an exception is printed on the System.err stream and format it.
    If this option would be availble in the debugger only, that would be ok too, I guess. Although, the debugger already has some other means of jumping through code when an exception is thrown (ie, when the debugger 'pauses' runtime).

    I've logged an Enhancement request to improve the handling of System.err messages (2811508). There are ways to enhance the treatment of System.err messages without introducing a new tab, through the use of color, links back to the source code, and collapsing of entire stack traces to a single line (with a button to see the entire trace).
    Thanks!
    -- Brian

  • Redirecting System.out to a JTextArea

    How can I redirect the System.out Stream into a JTextArea?
    I found the method System.setOut(PrintStream out) but I don't know
    how to get the PrintStream of my TextArea.

    I don't know if this is the most efficient way but it provides an example of using Pipes:
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TextAreaStream extends JTextArea implements Runnable{
         private static final PipedOutputStream _pipeOut = new PipedOutputStream();
         static{
                   System.setOut( new PrintStream(_pipeOut) );
         private InputStream _pipeIn;
    private byte[] buffer = new byte[256];
         public TextAreaStream(){
              this(1,10);
         public TextAreaStream(int numRows, int numCols){
              super(numRows, numCols);
              Thread t = new Thread(this);
              t.setDaemon(true);
              t.start();
              try{
              pipeIn =  new BufferedInputStream(new PipedInputStream(pipeOut));
              catch(IOException e){
                   System.err.println("Error creating pipe: "+e);
         public void run(){
              while(true){
                   try{
                        //blocks at read
                        int bytesRead = _pipeIn.read(buffer);
                        append(new String(buffer,0,bytesRead));
                   catch(IOException e){
                        System.err.println(e);
         public static void main(String[] args){
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JTextArea text = new TextAreaStream();
              text.setBorder(BorderFactory.createTitledBorder("System.out"));
              f.getContentPane().add(text);
              //Add an input component
              JPanel north = new JPanel(new FlowLayout(FlowLayout.LEFT));
              final JTextField field = new JTextField(25);
              north.add(field);
              north.add(new JLabel("Add text, press Enter"));
              f.getContentPane().add(north, BorderLayout.NORTH);
              field.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        System.out.println(field.getText());
                        field.setText("");
    f.setSize(600, 400);
              f.show();
    }

  • Redirecting System.out() output to a JTextArea control

    I want to be able to redirect System.out() and System.err() messages to a JTextArea control:
    I know how to redirect output to a file as follows:
    FileOutputStream fos =
    new FileOutputStream(filename, true);
    PrintStream ps = new PrintStream(fos, true);
    System.setOut(ps);
    System.setErr(ps);
    How can I set it up so that I can recognise when messages have been to System.out() with a view to displaying the message within the JTextArea?
    I guess I need to set it up so that the JTextArea control acts as an Observer. The bit I'm having difficulty with is figuring out how I can automatically determine when information has been written to System.out()?
    Hopefully I'm explaining my issue in enough detail and clarity.
    thanks
    - Garry

    I would suggest you set up a separate thread to monitor System.out. Use a PipedOutputStream and redirect System.out to that, then connect that to a PipedInputStream that your other thread is continually waiting to read. Each time that thread reads a line, it should append the line to the JTextArea, using SwingUtilities.invokeLater.
    This is just a rough outline of something that might work. Hope it helps.

  • System.out and System.err

    Hi all,
    This is a stupid newbie question, but I could not find the answer on the Web
    site, so here goes: Where do System.out and System.err get written to? I'm
    trying to deploy some plain-vanilla stateless session beans that do a bunch
    of println() calls, but I can't see the output anywhere! The WebLogic
    Console shows no messages, /myserver/weblogic.log has nothing interesting,
    and there are no .log files anywhere that I can see. I even searched /tmp
    and found nothing of interest. What am I missing? Do I have to explicitly
    open a file for System.out and/or System.err? That doesn't sound right...
    - danz

    The simple answer to your questions are no and no.
    I recently logged a problem with BEA WebLogic technical support regarding
    this issue and their response is:
    You have two choices. You can either use standard Java file i/o to write
    your output to a file, or you can use our t3loggingservices to append
    messages into the weblogic.log
    The "jump point" for the logging services is at --
    http://www.weblogic.com/docs51/classdocs/javadocs/weblogic/common/LogService
    sDef.html
    It is actually very easy to use -- after you import the proper packages into
    your web application it is just as easy to use as System.out.println.
    John J. Feigal Voice (651)766-8787 (main)
    Sr. Technical Consultant (651)766-7249 (direct)
    Ensodex, Inc. Fax (651)766-8792
    4105 N. Lexington Ave., Suite 150 email [email protected]
    Arden Hills, MN 55126 WebSite http://www.ensodex.com
    "Jon Wynett" <[email protected]> wrote in message
    news:[email protected]...
    I'm running WebLogic as an NT Service. Is there any way to see the
    System.out.println messages? Can they be redirected to the weblogic.log
    file?
    We were running through a DOS Window and saw all the messages, however we
    ideally want to run Weblogic as a service.
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]...
    I'm guessing that you started the server with the .exe file on Windows.
    If you're debugging with printlns, it's generally more conventient to
    use the startWebLogic.sh or startWebLogic.cmd files to start the server
    from a shell.
    By default, you'll see stdout and stderr in the window.
    -- Rob
    Dan Zivkovic wrote:
    Hi all,
    This is a stupid newbie question, but I could not find the answer on
    the
    Web
    site, so here goes: Where do System.out and System.err get written to?I'm
    trying to deploy some plain-vanilla stateless session beans that do abunch
    of println() calls, but I can't see the output anywhere! The WebLogic
    Console shows no messages, /myserver/weblogic.log has nothinginteresting,
    and there are no .log files anywhere that I can see. I even searched/tmp
    and found nothing of interest. What am I missing? Do I have toexplicitly
    open a file for System.out and/or System.err? That doesn't soundright...
    - danz

  • Redirecting System.out to a textfield

    I want the output created by System.out (especially error messages) redirected to a textfield in stead of the console. How can I do this?

    this is how I've done it. Just create a new instance of this class and pass in your TextArea. It redirects System.out and checks for messages on System.out every 5 seconds.
    import java.io.*;
    import javax.swing.*;
    public class TextOut
    implements Runnable
         private JTextArea text;
         private Reader in;
         private Thread t;
         public TextOut( JTextArea text )
              throws Exception
              this.text = text;
              PipedOutputStream pout = new PipedOutputStream();
              System.setOut( new PrintStream( pout ) );
              in = new InputStreamReader( new PipedInputStream( pout ) );
              t = new Thread( this );
              t.start();
         public void run()
              while( true )
                   try
                        StringBuffer buffer = null;
                        while( in.ready() )
                             if ( buffer == null ) buffer = new StringBuffer();
                             buffer.append( (char)in.read() );
                        if ( buffer != null )
                             text.append( buffer.toString() );
                             java.awt.Rectangle r = new java.awt.Rectangle();
                             text.computeVisibleRect( r );
                             text.repaint( r );
                        t.sleep( 5000 );
                   } catch (IOException ioe) {
                        text.append( "" + ioe );
                   } catch (InterruptedException ie ) {
                        text.append( "" + ie );

  • One JVM with different system.out / system.err files

    I have a menu application which allows me to launch different swingapps which runs inside one single JVM.
    All applications have their own properties.file which is read and handled at the start of each application.
    One property allows me to print all kind of system.err / system.out which i want to redirect to a specific file. This is implemented with following code:
            if (isTRACE_ENABLED()){
                try {
                    setTrace_out_log(new PrintStream(
                              new BufferedOutputStream(
                                    new FileOutputStream(props.getProperty("TRACE_OUTLOG_FILE")),128), true));
                    System.setOut(getTrace_out_log());
                    setTrace_err_log(new PrintStream(
                            new BufferedOutputStream(
                                  new FileOutputStream(props.getProperty("TRACE_ERRLOG_FILE")),128), true));
                    System.setErr(getTrace_err_log());
                } catch(IOException e) {
                    e.printStackTrace();
            }This works file but... all system.out and system.err is redirected to same file... which is not what i want.
    Example:
    debug property for menu application = enabled
    debug property for app 1 = disabled
    debug property for app 2 = enabled
    In above case i want to have 4 new files:
    - menuapp_out
    - menuapp_err
    - app2_out
    - app2_err
    This doesn't work, the files are created but after starting app2, the print-statements for the menu application are alse redirected to the app_2_xxx files. And when i finish app2, i do not get any print-output anymore
    IMHO this is because the JVM only has 1 system.out and 1 system.err file. Is there some way to solve this?

    I understand that i need to use java.util.logger (JUL) or Log4j
    Are there any (free) tools availabe to read/analyze the logfiles created by above tools?

Maybe you are looking for

  • Are there any timesten installation for data warehouse environment?

    Hi, I wonder if there is a way to install timesten as an in memory database for data warehouse environment? The DW today consist of a large Oralcle database and I wonder if and how a timesten implementation can be done. what kind of application chang

  • Error in bean lookup

    Hi,      I deployed a stateless session bean. When i do lookup in a jsp i am getting the following error. The application log file shows application is deployed successfully. The code in my jsp is: a Hashtable env = new Hashtable();      env.put ("ja

  • Use of staticCreatePrototypeResource method during Resource configuration

    Does anyone know when the staticCreatePrototypeResource method of an adapter is called? I am trying to create a custom adapter that accepts various different modules to actually do the provisioning. The problem I am having is making the prototypeXML

  • SelectOneMenu with properties file

    hi guys, I've got a problem with selectOneMenu. Basically setting the itemValue to static text is ok and everything works fine <f:selectItem itemLabel="#{others['dr']}" itemValue="Dr" />but if I set the itemValue to a property, I get a NullPointerExc

  • Graduated Filter creates saturated image

    Still getting to grips with Lightroom 3 and the graduated filter is working in strange ways. When I apply it the whole image goes super saturated and high in contrast. I have to click back in the history and then back on to the latest adjustment to m