There are at least two approaches for handling various exceptions that occur during an attempt to convert a character literal to a value of type DATE :
- Define as many exception names and associate them with Oracle error codes using
exception_init pragma, since many to_date() exceptions can raise a function. - Create a standalone or part of a package wrapper function for the
to_date() function, with one exception handler when others .
Personally, I lean toward the second.
SQL> create or replace package util1 as 2 function to_date1( 3 p_char_literal in varchar2, 4 p_date_format in varchar2 5 ) return date; 6 end; 7 / Package created SQL> create or replace package body util1 as 2 3 function to_date1( 4 p_char_literal in varchar2, 5 p_date_format in varchar2 6 ) return date is 7 begin -- in this situation it'll be safe to use `when others`. 8 return to_date(p_char_literal, p_date_format); 9 exception 10 when others then 11 raise_application_error(-20001, 'Not a valid date'); 12 end; 13 14 end; 15 / Package body created
Now only one exception is thrown -20001 Not a valid date , and your PL / SQl block might look like this:
SQL> set serveroutput on; -- [1] otherwise, for '1311313' the ORA-01830 exception would be raised SQL> declare 2 not_a_valid_date exception; 3 pragma exception_init(not_a_valid_date, -20001); 4 l_res date; 5 begin 6 l_res := util1.to_date1('1311313', 'yymmdd'); 7 exception 8 when not_a_valid_date then 9 dbms_output.put_line(sqlerrm); 10 -- or other handler sop('date format is wrong'); 11 end; 12 / ORA-20001: Not a valid date -- [2] otherwise, for '000000' the ORA-01843(not a valid month) -- exception would be raised SQL> declare 2 not_a_valid_date exception; 3 pragma exception_init(not_a_valid_date, -20001); 4 l_res date; 5 begin 6 l_res := util1.to_date1('000000', 'yymmdd'); 7 exception 8 when not_a_valid_date then 9 dbms_output.put_line(sqlerrm); 10 -- or other handler sop('date format is wrong'); 11 end; 12 / ORA-20001: Not a valid date
Nick Krasnov
source share