Converting a String to Date and raising an exception when given String is invalid

前端 未结 1 1514
星月不相逢
星月不相逢 2020-12-20 06:11

Here is my code given below. I want if the date given is incorrect it should display a message that is \"The format provided is incorrect\".

But I cant get it to rai

相关标签:
1条回答
  • 2020-12-20 06:46

    There are many exception which can be thrown by the TO_DATE function. Examples:

    • ORA-01843 - Invalid month value
    • ORA-01847 - Invalid day value
    • ORA-01830 - date format picture ends before converting entire input string
    • ...

    You can catch them as in the following example (with only one exception):

    Create or Replace Procedure A1SF_TESTDATE
    (
        pDateStr Varchar2
    
        -- you must do this for every oracle exception number which will you catch
        bad_month EXCEPTION;
        PRAGMA EXCEPTION_INIT (bad_month, -01843);
    )As
        tDate Date;
        Begin
        tdate := TO_DATE(pDateStr, 'yyyymmdd');
        dbms_output.put_line(tdate);
        Exception 
          When bad_month Then
            dbms_output.put_line('The format provided is incorrect');
    
    End;
    

    But for that you must define n pragmas!

    The easier solution, which I prefer, is:

    Create or Replace Procedure A1SF_TESTDATE
        (
            pDateStr Varchar2
        )As
            tDate Date;
    Begin
            tdate := TO_DATE(pDateStr, 'yyyymmdd');
            dbms_output.put_line(tdate);
            Exception 
              -- every exception will be catched
              When others Then
                dbms_output.put_line('The format provided is incorrect! Because: ' || SQLERRM);
    
     End;
    

    A possible message for SQLERRM is ORA-01847: day of month must be between 1 and last day of month.

    0 讨论(0)
提交回复
热议问题