2014-08-31 3 views
3

저는 Java에서 오류를 청취하는 방법을 알아 내려고하고 있습니다. 내가하고 싶은 일은 콘솔에 오류가 발생하면 프로그램이이를 감지하고 단순화합니다 (스택 추적은 무서울 수 있습니다!).로그에서 발생한 오류를 어떻게 수신합니까?

는 여기에 내가 뭘하려 :

 Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() 
     { 
      @Override 
      public void uncaughtException(Thread t, Throwable e) 
      { 
       // do some good stuff here, like logging or sending an alert email to the Support team 
       System.out.println("EXCEPTION CAUGHT!"); 
       System.out.println(e.getMessage()); 
      } 
     }); 

그러나 불행하게도, 예외 잡힌 말 아니에요! 오류가 발생하면 이 방법으로해야할까요, 아니면 System.out 로그 자체가 업데이트 될 때이를 청취 할 수있는 방법이 있습니까?

+0

이것은 스레드에서 캐치되지 않은 예외를 처리하는 방법 일뿐입니다. 당신은 당신이 여기에서 상상할 수있는 것을 할 수 있습니다. 정답은 없습니다. Log4J에는 로깅을위한 몇 가지 솔루션이 있습니다. 내 처리기에 전자 메일을 보내고 오류보고 양식을 작성하게했습니다. 필요한 작업을 지정했습니다. 일반적으로 오류를 기록하는 것은 좋은 습관입니다. –

+0

단순화 부분, 나는 알아낼 수있을 것 같아요. 나는 오류가 잡히지 않고 throw 될 때 메서드를 트리거하려고합니다. 그 후 서버 소유자가 오류가 무엇인지 알 수 있도록 간단하게 만듭니다 (저는 이것을 Bukkit 플러그인으로 코딩하고 있습니다). – ColonelHedgehog

+0

->'MyClass.doSomething (t, e);'당신은 기본적으로 "uncaughtException"메소드에서이 작업을 수행하고 있습니다. 기본적으로 모든 작업을 수행 할 수 있습니다. –

답변

2

답변이 부족하지만 많은 토론이있을 수 있습니다. 예를 들어 거의 모든 웹 프레임 워크에서 예외를 삼키는 사용자 지정 처리기가 프레임 워크에서 설정됩니다.

기본 처리기가 있고 각 스레드 또는 스레드 그룹이 자체 처리기를 가질 수있는 것처럼 작동하는 방법을 보여주는 코드가 있습니다. (당신이 버튼을 클릭하면 또는 비슷한)

import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 

    import javax.swing.JButton; 
    import javax.swing.JFrame; 
    import javax.swing.SwingUtilities; 


    public class Tests 
    { 
     public static void main(String ... args) 
     {  
      Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() 
      { 

       @Override 
       public void uncaughtException(Thread t, Throwable e) 
       { 
        System.out.print("[Handler Handling]\t"); 
        System.out.print(t.getName()); 
        System.out.print("\n"); 
        e.printStackTrace(System.out); 
        System.out.println("[End Handling]"); 
       } 
      }); 

      new Thread() 
      { 
       { 
        //Disable this handler 
        this.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { 

         @Override 
         public void uncaughtException(Thread thread, Throwable throwable) { 
          System.out.print("[Different Handling]\t"); 
          System.out.print(thread.getName()); 
          System.out.print("\n"); 
          throwable.printStackTrace(System.out); 
          System.out.println("[End Different Handler]"); 
         } 
        }); 
       } 
       public void run() 
       { 
        throw new RuntimeException("This is thrown in the child thread."); 
       } 
      }.start(); 

      try 
      { 
       Thread.sleep(500); 
      } 
      catch (InterruptedException e1) 
      { 
       e1.printStackTrace(); 
      } 

      JFrame gui = new JFrame(); 
      gui.setSize(400, 300); 
      gui.setTitle("Swing Thread"); 
      JButton error = new JButton("Throw Error"); 
      error.addActionListener(
       new ActionListener() 
       { 
        @Override 
        public void actionPerformed(ActionEvent arg0) 
        { 
         throw new RuntimeException("This exception happens in the Swing thread"); 
        } 

       }); 

      gui.add(error); 
      gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      gui.setVisible(true); 

      throw new RuntimeException("This is thrown in the main thread."); 
     } 
    } 

다음과 같은 출력을 제공합니다 :

[Different Handling] Thread-0 
java.lang.RuntimeException: This is thrown in the child thread. 
    at Tests$2.run(Tests.java:45) 
[End Different Handler] 
[Handler Handling] main 
java.lang.RuntimeException: This is thrown in the main thread. 
    at Tests.main(Tests.java:77) 
[End Handling] 
[Handler Handling] AWT-EventQueue-0 
java.lang.RuntimeException: This exception happens in the Swing thread 
    at Tests$3.actionPerformed(Tests.java:68) 
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) 
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) 
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) 
    <...snipped for brevity...> 
[End Handling] 

그래서 더 많은 정보없이 완벽하게 귀하의 질문에 대답하는 것은 불가능합니다. 예를 들어, JavaFX를 사용하는 경우 캡처되지 않은 예외를 처리하기위한 다른 패턴이 있습니다. 전적으로 프레임 워크와 상황에 달려 있습니다. 만약 당신이 사실, 메인 스레드에서 핸들러를 설정하고 거기서 시작하면 문제없이 작동 할 것입니다.

관련 문제