如何在Java中使用自定义异常?我已经按照步骤操作,但是没有使catch子句起作用

时间:2018-09-08 02:52:45

标签: java exception try-catch

我已经花费了数小时试图弄清楚我的Java异常处理出了什么问题。我遵循了所有书籍和网站的内容,以创建海关例外,将它们扔掉并试图抓住它们。它们正在扩展RuntimeException(因为它们被引发在ActionEvent中),所以我认为throws子句不需要在方法标题中声明。但是catch子句不会运行。以下是相关代码:

public void handle(ActionEvent event){
        Object selectedButton = event.getSource();
        if (selectedButton == b1)
        {
            String passwordStr1 = password1.getText(); 
            String passwordStr2 = password2.getText();
            {
                if(passwordStr1.equals(passwordStr2))
                {

                if(PasswordCheckerUtility.isValidPassword(passwordStr1)== true)
                    {
                        Alert validAlert = new Alert(AlertType.INFORMATION);
                        validAlert.setTitle("Password Status");
                        validAlert.setHeaderText("Password is valid");
                        validAlert.showAndWait();
                    }


              else
                try
                {
                    throw new UnmatchedException("The passwords do not match");
                }
                catch(UnmatchedException ue) {
                    Alert unEAlert = new Alert(AlertType.ERROR);
                    unEAlert.setTitle("Password Status");
                    unEAlert.setContentText(ue.getMessage());
                }
            }
        }

public class UnmatchedException extends RuntimeException{

    public UnmatchedException(String message)
    {
        super(message);
    }

}

2 个答案:

答案 0 :(得分:1)

我尝试了一个更基本的示例,它似乎起作用了。也许问题出在代码的其他方面。这是我用的:

主要方法:

public static void main(String...args){
    handle(null);
}//main()

handle方法:

public static void handle(ActionEvent event){
    try {
        throw new UnmatchedException("The passwords do not match");
    } catch(UnmatchedException ue) {
        System.out.println(ue.getMessage());
    }
}

和自定义异常在单独的类中

public class UnmatchedException extends RuntimeException{
    private static final long serialVersionUID = 1L;

    public UnmatchedException(String message)
    {
        super(message);
    }
}

答案 1 :(得分:1)

不太确定为什么要使用相同的方法引发/捕获异常。

异常处理相对昂贵,应该尽可能避免。在您的简单示例中,您只是尝试显示警报消息。这可以在“其他声明”中轻松完成。

通常,仅当您希望调用该方法的代码来处理该异常时,才抛出该异常。

在任何情况下,以相同的方法抛出并捕获Exception对我来说都很好:

Sub Emails_Outlook()
'Carregar e-mails do outlook para o excel
Dim appOutlook As Object
Dim olNS As Object
Dim olFolder As Object
Dim olItem As Object
Dim r As Long
Dim Ws As Worksheet
Dim LstObj As ListObject
Dim rngDB As Range, n As Integer

On Error Resume Next
Set appOutlook = GetObject(, "Outlook.Application")
If appOutlook Is Nothing Then
Set appOutlook = CreateObject("Outlook.Application")
End If
On Error GoTo 0
Set olNS = appOutlook.GetNamespace("MAPI")
'Abaixo preencha o nome do arquivo de dados PST e a pasta.
'Neste caso o arquivo é Douglas Godoy e a pasta Caixa de Entrada.
Set olFolder = olNS.Folders("vaz.felipe@outlook.com.br").Folders("Caixa de Entrada").Folders("Teste")
Cells.Delete
r = 3
'Cria um array montando o título das colunas no arquivo.
Range("A3:E3") = Array("Título", "Quem enviou", "Nome de quem enviou", "Para", "Data e Hora")
For Each olItem In olFolder.Items
If TypeName(olItem) = "MailItem" Then
r = r + 1
Cells(r, "A") = olItem.Subject 'Assunto do e-mail
Cells(r, "B") = olItem.SenderEmailAddress 'E-mail do remetente
Cells(r, "C") = olItem.Sender 'Nome do remetente
Cells(r, "D") = olItem.To 'E-mail do destinatário
Cells(r, "E") = olItem.ReceivedTime 'Data/Hora de recebimento

'Cells(r, "E") = olItem.Attachments.Count 'Número de anexos
'Cells(r, "F") = olItem.Size 'Tamanho da mensagem em bytes
'Cells(r, "G") = olMail.LastModificationTime 'Última modificação
'Cells(r, "H") = olMail.Categories 'Categoria
'Cells(r, "I") = olMail.SenderName 'Nome do remetente
'Cells(r, "J") = olMail.FlagRequest 'Acompanhamento
'Cells(r, "K") = olItem.Body 'Tome cuidado ao utilizar pois carrega os dados do corpo do email
Application.StatusBar = r
End If
Next olItem

For Each Ws In Worksheets
        With Ws
            Set rngDB = .Range("a3").CurrentRegion
            For Each LstObj In Ws.ListObjects
                LstObj.Unlist
            Next
            If WorksheetFunction.CountA(rngDB) > 0 Then
                n = n + 1
                Set LstObj = .ListObjects.Add(xlSrcRange, rngDB, , xlYes)
                With LstObj

                    .Name = "AtendimentoPresencial" '& n
                    .TableStyle = "TableStyleLight8"
                End With
            End If
        End With
    Next Ws

Columns.AutoFit
End Sub

学习新概念时,从简单的代码开始并使其生效,然后将知识应用于您的实际应用程序将变得更加容易。此问题可能是由您的验证逻辑引起的。