2015-10-13 145 views
0

即使我输入了自定义消息,但在发出消息时未打印该消息。下面的代码:自定义异常抛出正在打印为空的消息

public void run() throws Exception { 

     try{ 

     String poNumber=null; 
        if(poNumber.equals(null)) 
        { 
         throw new Exception("Services Purchase Order not created."); 
        } 
      } 



       catch (Exception e) { 


        info("Custom Exception Message: "+e.getMessage()); 

       } 

OUTPUT:

自定义异常消息:空

回答

1

您还没有抛出自己的Exception;您因poNumbernull而导致NullPointerExceptionpoNumber.equals(null)

你的catch块抓到NullPointerException,而不是你的Exception,它的消息是null

如果您确实想自己抛出Exception,则更改条件使用==,以避免NullPointerException

if (poNumber == null) 
0

公共无效的run()抛出异常{

try{ 

    String poNumber=null; 
       if(poNumber==null) 
       { 
        throw new Exception("Services Purchase Order not created."); 
       } 
     } 



      catch (Exception e) { 


       info("Custom Exception Message: "+e.getMessage()); 

      } 

这会给你的消息,你想

0

您正赶上了错误的例外:

poNumber.equals(null) 

会导致在NullPointerException(因为你不能拨打等于null)。 你必须重写它是这样的:

if(null == poNumber) 
{ 
    throw new Exception("Services Purchase Order not created."); 
} 

根据您的日志framwork您还可以调整你的信息()调用是这样

info("Exception occured", e); 

所以你会知道下一次它出现异常。