Exception handling in mutator versus constructor

Hello,
In my class, an AlchemicIngredient has a basicName. This name has to be fit under certain strict regulations on which we have to check (see my last question on the pattern class). Ofcourse I made a static verifier to check this called isValidBasicName(String name) returning a boolean. However, upon creation a name can not contain the words 'mixed with', but the method mixWith(AlchemicIngredient other) must place this 'mixed with' in the basicName. It does that through setBasicName(String newName). setBasicName, however will throw an exception if this string does not comply to isValidBasicName.
I see some possible solutions:
1. do not throw the IllegalBasicNameException in the setBasicName, and throw it directly in the constructor upon performing the isValidBasicName check. This, however means, that the setBasicName wil never check if the name is valid.
2. create a second form of isValidBasicName, that does tolerate "mixed with" in the basicName and use this verifier in every method except for the constructor.
3. do not use the setter in the class itself, and just change the instantion variable directly, this seems however very unsecure and styleless.
Any other suggestions? Which do you think seems the best? We need to write the name handling in a defensive way.
And if i remember correctly, when you throw an exception in the middle of a try-block, it will skip the rest of the try block, no? Or am I wrong?
Greetings, Royo

It sounds like you have two conditions to test for:
isValidBasicName
and
isValidInitialBasicName.
I'd have the c'tor call the second one, and throw the exception if it's false, and I'd have the setter call the first one and throw the exception if it's false.
Additionally, the second one would call the first one, and also do the addition check that there's no "mixed with."

Similar Messages

  • Pls help..Constructor,setter, getter and Exception Handling Problem

    halo, im new in java who learning basic thing and java.awt basic...i face some problem about constructor, setter, and getter.
    1. I created a constructor, setter and getter in a file, and create another test file which would like to get the value from the constructor file.
    The problem is: when i compile the test file, it come out error msg:cannot find symbol.As i know that is because i miss declare something but i dont know what i miss.I post my code here and help me to solve this problem...thanks
    my constructor file...i dont know whether is correct, pls tell me if i miss something...
    public class Employee{
         private int empNum;
         private String empName;
         private double empSalary;
         Employee(){
              empNum=0;
              empName="";
              empSalary=0;
         public int getEmpNum(){
              return empNum;
         public String getName(){
              return empName;
         public double getSalary(){
              return empSalary;
         public void setEmpNum(int e){
              empNum = e;
         public void setName(String n){
              empName = n;
         public void setSalary(double sal){
              empSalary = sal;
    my test file....
    public class TestEmployeeClass{
         public static void main(String args[]){
              Employee e = new Employee();
                   e.setEmpNum(100);
                   e.setName("abc");
                   e.setSalary(1000.00);
                   System.out.println(e.getEmpNum());
                   System.out.println(e.getName());
                   System.out.println(e.getSalary());
    }**the program is work if i combine this 2 files coding inside one file(something like the last part of my coding of problem 2)...but i would like to separate them....*
    2. Another problem is i am writing one simple program which is using java.awt interface....i would like to add a validation for user input (something like show error msg when user input character and negative number) inside public void actionPerformed(ActionEvent e) ...but i dont have any idea to solve this problem.here is my code and pls help me for some suggestion or coding about exception. thank a lots...
    import java.awt.*;
    import java.awt.event.*;
    public class SnailTravel extends Frame implements ActionListener, WindowListener{
       private Frame frame;
       private Label lblDistance, lblSpeed, lblSpeed2, lblTime, lblTime2, lblComment, lblComment2 ;
       private TextField tfDistance;
       private Button btnCalculate, btnClear;
       public void viewInterface(){
          frame = new Frame("Snail Travel");
          lblDistance = new Label("Distance");
          lblSpeed = new Label("Speed");
          lblSpeed2 = new Label("0.0099km/h");
          lblTime = new Label("Time");
          lblTime2 = new Label("");
          lblComment = new Label("Comment");
          lblComment2 = new Label("");
          tfDistance = new TextField(20);
          btnCalculate = new Button("Calculate");
          btnClear = new Button("Clear");
          frame.setLayout(new GridLayout(5,2));
          frame.add(lblDistance);
          frame.add(tfDistance);
          frame.add(lblSpeed);
          frame.add(lblSpeed2);
          frame.add(lblTime);
          frame.add(lblTime2);
          frame.add(lblComment);
          frame.add(lblComment2);
          frame.add(btnCalculate);
          frame.add(btnClear);
          btnCalculate.addActionListener(this);
          btnClear.addActionListener(this);
          frame.addWindowListener(this);
          frame.setSize(100,100);
          frame.setVisible(true);
          frame.pack();     
        public static void main(String [] args) {
            SnailTravel st = new SnailTravel();
            st.viewInterface();
        public void actionPerformed(ActionEvent e) {
           if (e.getSource() == btnCalculate){
              SnailData sd = new SnailData();
           double distance = Double.parseDouble(tfDistance.getText());
           sd.setDistance(distance);
                  sd.setSpeed(0.0099);
              sd.setTime(distance/sd.getSpeed());
              String answer = Double.toString(sd.getTime());
              lblTime2.setText(answer);
              lblComment2.setText("But No Exception!!!");
           else
           if(e.getSource() == btnClear){
              tfDistance.setText("");
              lblTime2.setText("");
       public void windowClosing(WindowEvent e){
                   System.exit(1);
        public void windowClosed (WindowEvent e) { };
        public void windowDeiconified (WindowEvent e) { };
        public void windowIconified (WindowEvent e) { };
        public void windowActivated (WindowEvent e) { };
        public void windowDeactivated (WindowEvent e) { };
        public void windowOpened(WindowEvent e) { };
    class SnailData{
       private double distance;
       private double speed;
       private double time;
       public SnailData(){
          distance = 0;
          speed = 0;
          time = 0;
       public double getDistance(){
          return distance;
       public double getSpeed(){
          return speed;
       public double getTime(){
          return time;
       public void setDistance(double d){
          distance = d;
       public void setSpeed(double s){
          speed = s;
       public void setTime(double t){
          time = t;
    }Pls and thanks again for helps....

    What i actually want to do is SnailTravel, but i facing some problems, which is the
    - Constructor,setter, getter, and
    - Exception Handling.
    So i create another simple contructor files which name Employee and TestEmployeeClass, to try find out the problem but i failed, it come out error msg "cannot find symbol".
    What i want to say that is if i cut below code (SnailTravel) to its own file(SnailData), SnailTravel come out error msg "cannot find symbol".So i force to put them in a same file(SnailTravel) to run properly.
    I need help to separate them. (I think i miss some syntax but i dont know what)
    And can somebody help me about Exception handling too pls.
    class SnailData{
       private double distance;
       private double speed;
       private double time;
       public SnailData(){
          distance = 0;
          speed = 0;
          time = 0;
       public double getDistance(){
          return distance;
       public double getSpeed(){
          return speed;
       public double getTime(){
          return time;
       public void setDistance(double d){
          distance = d;
       public void setSpeed(double s){
          speed = s;
       public void setTime(double t){
          time = t;

  • Exception handling for Scanner console input

    I'm trying to add exception handling to a Scanner console to deal with exceptions caused by non-numeric input. My idea was to do use a try/catch in a for loop and break if no exception occurs.
    Whats happening is the "iNumber = console.nextInt(); " does nothing on subsequent retries, when an exception occurs. That is, I enter "123w", an InputMismatchException occurs, goes into the first catch block, hits "continue" and goes back into the for loop, hits the "iNumber = console.nextInt(); ", then immediately blows through it without executing. Thus, I hit my max loop count and exit with iNumber = 0.
    I'm thinking I may need to instantiate "static Scanner console = new Scanner(System.in);" again in the event of an exception?
    Thanks for any feedback. I'm brand new at Java and learning as fast as I can :)
    Here is the code:
    class ConsoleInput
         public ConsoleInput() // constructor
         static Scanner console = new Scanner(System.in);
         public int GetInput()
              int iNumber = 0;
              for(int i=0; i<3; i++)
              try
                   System.out.print("Please enter a number: ");
                   iNumber = console.nextInt(); // get console input
                   break;
              catch(java.util.InputMismatchException ex)
                   continue;
              catch(Exception ex)
                   continue;
         return iNumber;
    }

    public class Scratch {
      public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean gotAValidInt = false;
        int theInt;
        System.out.println("Enter an int");
        do {
          try {
            theInt = sc.nextInt();
            gotAValidInt = true;
          catch (InputMismatchException exc) {
            System.out.println("Not an int. Try again.");
            sc.next(); // consume the non-int that nextInt couldn't consume
        } while (!gotAValidInt);
    }There are different ways you could structure your loop, but the key is that when nextInt throws an exception, you have to call next() in the catch block to consume the token that nextInt couldn't.
    Edited by: jverd on May 2, 2008 1:52 PM

  • Exception handling in stored process, loop IF..ELSE

    Hello Guys,
    we want to put in exception handling in the loop but get the following error:
    Error(43,3): PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: begin case declare end exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimited-identifier> <a bind variable> << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe
    create or replace
    PROCEDURE xxxx
    FOR MESSSY IN
    select I.*
    FROM x I
    LOOP
    IF upper(CODE)='N' THEN
    INSERT INTO T_MESS(MP)
    select I.MP_ID
    FROM T_ME
    ELSIF upper(MESSSY.k2)='L' THEN
    DELETE T_MESS WHERE T_MESS.MP = MESSSY.MP;
    END IF;
    EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
    A program attempted to insert duplicate values in a column that is constrained by a unique index.
    DBMS_OUTPUT.PUT_LINE ('A program attempted to insert duplicate values in a column that is constrained by a unique index.')
    --No Rollback
    END;
    COMMIT;
    END LOOP;
    END xxxx;
    does someone know why?

    BluShadow wrote:
    Well, your code is missing all sorts of bits and we don't have your data or your exact logic to know what it's supposed to be achieving.
    That is right, you dont have my data and that is why I was suprised by your comment.
    Since the input table might contain a few thousand rows and each of those might need to
    be considered N , D, or C and each case has a different handling I can not imagine how this
    can be all done with a merge statement.
    MERGE
    T_METRICPOINT_META with T_METRICSSYSTEM_LOAD where T_METRICSSYSTEM_LOAD .LOAD_DATE=to_char(sysdate)
    WHEN MATCHED THEN --we know those are the metric points that have to be loaded today, but we still need to do a IF..ELSE to handle them
    WHEN NOT MATCHED THEN -- not considered in todays load
    ----original code-----
    create or replace
    PROCEDURE myprocedure AS
    BEGIN
    --Extracting the records from T_METRICSSYSTEM_LOAD which have todays load date. Corresponding to these MP_System, we extract the MP_IDs from the T_METRICPOINT_META table.
    --Comapring these MP_IDs with the MP_IDs from the source(T_METRICPOINT_IMPORT) and extracting only those Metric points which need to be loaded today.
    FOR METRICSSYSTEM IN
    select I.*
    FROM T_METRICPOINT_IMPORT I
    where I.LOADDATE = TO_CHAR(SYSDATE) AND I.MP_ID IN
    (select a.MP_ID
    from T_METRICPOINT_META a INNER JOIN T_METRICSSYSTEM_LOAD b on a.MP_SYSTEM = b.MP_SYSTEM where b.LOAD_DATE=to_char(sysdate))
    LOOP
    --If mutation code in the source/import data is "N", the record is inserted as it is in the "T_METRICPOINTS" table.
    IF upper(METRICSSYSTEM.MUTATIONCODE)='N' THEN --new
    INSERT INTO T_METRICPOINTS(MP_ID, ......)
    SELECT DISTINCT I.MP_ID,.....
    FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
    ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='D' THEN --delete
    DELETE T_METRICPOINTS WHERE T_METRICPOINTS.MP_ID = METRICSSYSTEM.MP_ID AND T_METRICPOINTS.KEY = METRICSSYSTEM.KEY;
    ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='C' THEN --correction
    UPDATE T_HISTORYMETRICPOINTS H
    SET CHANGE_DATE = to_char(sysdate)
    WHERE H.MP_ID=METRICSSYSTEM.MP_ID AND H.KEY = METRICSSYSTEM.KEY;
    INSERT INTO T_HISTORYMETRICPOINTS(MP_ID, KEY, .....)
    --The distinct here is used, to handle 2 identical records in the input table with correction value "C". This would insert into 1 record in the T_HISTORYMETRICPOINTS table without
    --violating the primary key constraint.
    select DISTINCT I.MP_ID,I.KEY, ....
    FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
    --END IF;
    END IF;
    COMMIT;
    END LOOP;
    END myprocedure;

  • RFC: Exception handling

    Hi there,
    after playing a bit with external xml files provided by my
    application i'm ready to go to the next topic on my ToDo-List.
    How could one implement a good and stable technique for
    exception handling? I'm talking about the interaction from spry to
    our Web Framework which throws an error sometimes.
    My current idea is that the server side framework could
    return some kind of Error XML format which contains the exception
    message and so on. This would require functions on client side to
    precheck the server output.
    Imho the best place for this is inside the XMLDataSet
    constructor. When catching some bad XML file internal error
    messages could be send using the already existing techniques OR by
    providing an public function which then should be overriden by an
    selfwritten one, e.g. to put it into my own `error box`.
    Also, some kind of internal statemachine in XMLDataSet may
    help a lot. That way each access to functions which aren't working
    at the moment could be loggend and catched by an selfwritten
    function.
    I hope you get the idea,
    what do you think?
    Best regards,
    Sebastian

    Better error handling and error handling hooks is on the list
    of things to do.
    The way I see it, there are several types of errors that can
    occur:
    1. Server returns valid XML, but it's XML that describes an
    error instead of the data requested.
    - I believe this is what Sebastian was mentioning. I was
    actually thinking of allowing a hook for developers to catch and
    handle this case and perhaps leverage the states mechanism to let
    them change the dynamic region markup used to display the error
    since the data references in this error XML would be different.
    2. The server returns an error. (Invalid URL or Server Error)
    - This could be handled with states, but we need to expose
    some data references, or set the data set to contain a known data
    set schema that would allow the designer to show more info about
    the error.
    3. The server returns XML but uses a mime-type that is not
    understood by Spy or the XML parsing code built-into the browser.
    - I believe it was Doug [?] that had a patch that *always*
    forced the data set to try and parse the XML string in the response
    if the response didn't contain an XML DOM. My one paranoia about
    that is that the server could actually be returning something that
    is not XML, in which we would still fail and perhaps choke
    somewhere else. I need to do some testing in that area.
    I was thinking perhaps we should add something to the
    XMLDataSet constructor that allowed a user to specify mime-types
    for formats they knew were XML, but didn't use one of the standard
    XML formats.
    4. The browser chokes on "not-well-formed" XML.
    - This is an interesting problem. IE silently fails when the
    parser chokes, but Mozilla creates an XML DOM tree that reports the
    error which does *not* match the XML string from the request
    response. I had to add code to spry to detect when this happens.
    5. An exception is thrown during Spry processing of XML data.
    - This will require more programming on our part to handle
    more cases.
    --== Kin ==--

  • Customised Exception handling class.....

    Hello Friends,
    I am working on a project for which I need to create my own exception handling class.
    The reason I need this class is to catch any exceptions and get a customised error message
    according to each exception and then be able to display those messages on web page.
    some examples of the exception I want to catch and display appropriate message are..
    1. a duplicate reord in db
    2. wrong data type (this will deal with ints,doubles and strings data types)
    3. date type validation ( to make sure its date object instead of a string)
    and there are several more messages but if can get some help or idea from any one to design a class for the above errors I might be able to manage other errors as well.
    greatly appreciate any respnses.

    First off, you can extend Exception:
    public class MyException extends Exception {
    }You can put some custom messages into the class:
    public class MyException extends Exception {
      public static final String DUPLICATE_RECORD = "Duplicate record in db",
                           WRONG_DATA_TYPE = "Wrong data type",
                           VALIDATION_ERROR = "Invalid data type";
    }Then, have your constructors, which take a String as an argument, so they can get your 'presets' or a custom message:
    public class MyException extends Exception {
      public static final String DUPLICATE_RECORD = "Duplicate record in db",
                           WRONG_DATA_TYPE = "Wrong data type",
                           VALIDATION_ERROR = "Invalid data type";
      public MyException(String message) {
        super(message);
    }You could also have a series of exception classes: DuplicateRecordException, WrongDataTypeException, ValidationException, etc. Hope that helps.
    m

  • Console Exception Handling.  Allow another attempt for user before exiting

    I am trying to implement a very simple program that prompts the user for info and reads in a few numbers. If the user accidentally enters a letter instead of a number I want the user to get another chance, not just execute the exception handler and exit the program (as it does now). I'd rather have the user get stuck in an endless loop waiting for valid input versus exiting on the first invalid entry.
    The code I am using is something like this:
    try{
       System.out.println("Enter a number?");
       int b=System.in.read();
       char c=(char) b;
       String s=String.valueOf(c);
       p.setDummyValue(Integer.parseInt(s) ); //**Possible Exception Here
    catch(NumberFormatException e) {
       System.out.println("Invalid Input");
       // *** I'd love to somehow return to the "Enter a number" line from here
    catch(IOException e) {
       //IO error code here
    }Q: How can I implement the ability to allow a user to correct invalid input?
    Thanks

    Something like this should work:boolean numberValid = false;
    while (!numberValid) {
         try {
              System.out.println("Enter a number?");
              int b=System.in.read();
              System.in.skip(System.in.available()); // skip carriage return
              char c=(char) b;
              String s=String.valueOf(c);
              p.setDummyValue(Integer.parseInt(s));
              numberValid = true;
         } catch(NumberFormatException e) {
              System.out.println("Invalid Input");
         } catch(IOException e) {
              //IO error code here
    }

  • Exception handling - more

    Okay, new day new questions.
    What's better?
    method ...() {
    try {
    doMethod1();
    catch (exception) {
    // handle error
    try {
    doMethod2();
    catch (exception) {
    // handle error
    }or
    method()...{
    try {
    doMethod1();
    doMethod2();
    catch (exception) {
    // handle exception
    }The question is readability and program flow. If you wrap up a chunk of a code block which contains methods that throw exceptions as well as those that don't, when you're reading back through it it's hard to know which methods throw exceptions and which don't. It's hard to see the flow of the program just by looking at the code.
    But if you wrap up every method in a try/catch that can throw an exception you make it just as hard to see the program flow since you're dealing with multiple exceptions where each catch handles the error in much the same way. Instead of breaking out of the method at one place you could now be breaking out at several.
    Comments? Suggestions?

    There's one more: don't catch anything and declare your method to throw them, that way the calling method gets thrown an exception containing not only a full stack trace but also a (supposedly) descriptive message.
    Of course we know that that is not always the case.
    I think the "best" way depends on circumstances. I was asked at a job interview, "How do you decide whether to catch and exceptions in a method or to have them throw 'em on up?". My answer was to stammer around a bit, then reply very cleverly with "It depends."
    HaHa, but I think it's true. It depends on the kind of program, the purpose of the method, and the potential uses of the method. (ps. the interviewer is now my boss, so maybe I was right?)
    A story from my past life: there was once a class/method, originally never intended to be used outside of its package and the single use they had in mind when they designed it. Unfortunately, time proved that this package has some useful stuff and it grew into kindof an widely used API within the company. However the class/method to which I refer was responsible for open a Socket connection (from an IP address string and string port number) to a device and communicating some bytes back and forth to initialize the device (can you count how many checked much less unchecked things can come out of that before you even do any validity checking???). However, this constructor caught all of its exceptions and handled them by writing to some logging system that existed only in the original system). Therefore, years later when I was writing a GUI that used this class, my GUI had no way of knowing if anything was wrong, much less what actually was wrong.
    The moral of the story is that I have come to believe in letting exceptions float up as high as reasonable, because you never know. (Of course I don't always practice this flawlessly.)
    /Mel

  • MC.9 and MCY1 and Exception Handling in (Logistics Inf. Sys)LIS

    Hi,
    I want the 'Valuated Stock Value" greater then or equal to zero (>=) appear in the MC.9 report. I can create 'Exception' in MCY1 but am unable to do so. Once I am in MCY1; I choose 'Requirements' then Key Figure 'Valuated Stock Value' then  'Type of condition' is 'Threshold Val. Anal.' is set to '> 0'. However, the report still displays zero values in MC.9. I don't want to display 'Valuated Stock Value' zero to be displayed on the report. Please help.
    Thanks
    Naved

    Hey Chris,
    I got the point for exception handling in weblogic 9.2. We ae using 9.2. It comes up with the concept of shared page flows which means all my unhandled exceptions are thrown to the shared page flow controller. There based on the type of exception, i can forward the request to appropraite page.
    Thanks anywyas,
    Saurabh

  • PL/SQL 101 : Exception Handling

    Frequently I see questions and issues around the use of Exception/Error Handling in PL/SQL.  More often than not the issue comes from the questioners misunderstanding about how PL/SQL is constructed and executed, so I thought I'd write a small article covering the key concepts to give a clear picture of how it all hangs together. (Note: the examples are just showing examples of the exception handling structure, and should not be taken as truly valid code for ways of handling things)
    Exception Handling
    Contents
    1. Understanding Execution Blocks (part 1)
    2. Execution of the Execution Block
    3. Exceptions
    4. Understanding Execution Blocks (part 2)
    5. How to continue exection of statements after an exception
    6. User defined exceptions
    7. Line number of exception
    8. Exceptions within code within the exception block
    1. Understanding Execution Blocks (part 1)
    The first thing that one needs to understand is almost taking us back to the basics of PL/SQL... how a PL/SQL execution block is constructed.
    Essentially an execution block is made of 3 sections...
    +---------------------------+
    |    Declaration Section    |
    +---------------------------+
    |    Statements  Section    |
    +---------------------------+
    |     Exception Section     |
    +---------------------------+
    The Declaration section is the part defined between the PROCEDURE/FUNCTION header or the DECLARE keyword (for anonymous blocks) and the BEGIN keyword.  (Optional section)
    The Statements section is where your code goes and lies between the BEGIN keyword and the EXCEPTION keyword (or END keyword if there is no EXCEPTION section).  (Mandatory section)
    The Exception section is where any exception handling goes and lies between the EXCEPTION keyword at the END keyword. (Optional section)
    Example of an anonymous block...
    DECLARE
      .. declarative statements go here ..
    BEGIN
      .. code statements go here ..
    EXCEPTION
      .. exception handlers go here ..
    END;
    Example of a procedure/function block...
    [CREATE OR REPLACE] (PROCEDURE|FUNCTION) <proc or fn name> [(<parameters>)] [RETURN <datatype>] (IS|AS)
      .. declarative statements go here ..
    BEGIN
      .. code statements go here ..
    EXCEPTION
      .. exception handlers go here ..
    END;
    (Note: The same can also be done for packages, but let's keep it simple)
    2. Execution of the Execution Block
    This may seem a simple concept, but it's surprising how many people have issues showing they haven't grasped it.  When an Execution block is entered, the declaration section is processed, creating a scope of variables, types , cursors, etc. to be visible to the execution block and then execution enters into the Statements section.  Each statment in the statements section is executed in turn and when the execution completes the last statment the execution block is exited back to whatever called it.
    3. Exceptions
    Exceptions generally happen during the execution of statements in the Statements section.  When an exception happens the execution of statements jumps immediately into the exception section.  In this section we can specify what exceptions we wish to 'capture' or 'trap' and do one of the two following things...
    (Note: The exception section still has access to all the declared items in the declaration section)
    3.i) Handle the exception
    We do this when we recognise what the exception is (most likely it's something we expect to happen) and we have a means of dealing with it so that our application can continue on.
    Example...
    (without the exception handler the exception is passed back to the calling code, in this case SQL*Plus)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3  begin
      4    select ename
      5    into   v_name
      6    from   emp
      7    where  empno = &empno;
      8    dbms_output.put_line(v_name);
      9* end;
    SQL> /
    Enter value for empno: 123
    old   7:   where  empno = &empno;
    new   7:   where  empno = 123;
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at line 4
    (with an exception handler, we capture the exception, handle it how we want to, and the calling code is happy that there is no error for it to report)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3  begin
      4    select ename
      5    into   v_name
      6    from   emp
      7    where  empno = &empno;
      8    dbms_output.put_line(v_name);
      9  exception
    10    when no_data_found then
    11      dbms_output.put_line('There is no employee with this employee number.');
    12* end;
    SQL> /
    Enter value for empno: 123
    old   7:   where  empno = &empno;
    new   7:   where  empno = 123;
    There is no employee with this employee number.
    PL/SQL procedure successfully completed.
    3.ii) Raise the exception
    We do this when:-
    a) we recognise the exception, handle it but still want to let the calling code know that it happened
    b) we recognise the exception, wish to log it happened and then let the calling code deal with it
    c) we don't recognise the exception and we want the calling code to deal with it
    Example of b)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3    v_empno NUMBER := &empno;
      4  begin
      5    select ename
      6    into   v_name
      7    from   emp
      8    where  empno = v_empno;
      9    dbms_output.put_line(v_name);
    10  EXCEPTION
    11    WHEN no_data_found THEN
    12      INSERT INTO sql_errors (txt)
    13      VALUES ('Search for '||v_empno||' failed.');
    14      COMMIT;
    15      RAISE;
    16* end;
    SQL> /
    Enter value for empno: 123
    old   3:   v_empno NUMBER := &empno;
    new   3:   v_empno NUMBER := 123;
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at line 15
    SQL> select * from sql_errors;
    TXT
    Search for 123 failed.
    SQL>
    Example of c)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3    v_empno NUMBER := &empno;
      4  begin
      5    select ename
      6    into   v_name
      7    from   emp
      8    where  empno = v_empno;
      9    dbms_output.put_line(v_name);
    10  EXCEPTION
    11    WHEN no_data_found THEN
    12      INSERT INTO sql_errors (txt)
    13      VALUES ('Search for '||v_empno||' failed.');
    14      COMMIT;
    15      RAISE;
    16    WHEN others THEN
    17      RAISE;
    18* end;
    SQL> /
    Enter value for empno: 'ABC'
    old   3:   v_empno NUMBER := &empno;
    new   3:   v_empno NUMBER := 'ABC';
    declare
    ERROR at line 1:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    ORA-06512: at line 3
    SQL> select * from sql_errors;
    TXT
    Search for 123 failed.
    SQL>
    As you can see from the sql_errors log table, no log was written so the WHEN others exception was the exception that raised the error to the calling code (SQL*Plus)
    4. Understanding Execution Blocks (part 2)
    Ok, so now we understand the very basics of an execution block and what happens when an exception happens.  Let's take it a step further...
    Execution blocks are not just a single simple block in most cases.  Often, during our statements section we have a need to call some reusable code and we do that by calling a procedure or function.  Effectively this nests the procedure or function's code as another execution block within the current statement section so, in terms of execution, we end up with something like...
    +---------------------------------+
    |    Declaration Section          |
    +---------------------------------+
    |    Statements  Section          |
    |            .                    |
    |  +---------------------------+  |
    |  |    Declaration Section    |  |
    |  +---------------------------+  |
    |  |    Statements  Section    |  |
    |  +---------------------------+  |
    |  |     Exception Section     |  |
    |  +---------------------------+  |
    |            .                    |
    +---------------------------------+
    |     Exception Section           |
    +---------------------------------+
    Example... (Note: log_trace just writes some text to a table for tracing)
    SQL> create or replace procedure a as
      2    v_dummy NUMBER := log_trace('Procedure A''s Declaration Section');
      3  begin
      4    v_dummy := log_trace('Procedure A''s Statement Section');
      5    v_dummy := 1/0; -- cause an exception
      6  exception
      7    when others then
      8      v_dummy := log_trace('Procedure A''s Exception Section');
      9      raise;
    10  end;
    11  /
    Procedure created.
    SQL> create or replace procedure b as
      2    v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
      3  begin
      4    v_dummy := log_trace('Procedure B''s Statement Section');
      5    a; -- HERE the execution passes to the declare/statement/exception sections of A
      6  exception
      7    when others then
      8      v_dummy := log_trace('Procedure B''s Exception Section');
      9      raise;
    10  end;
    11  /
    Procedure created.
    SQL> exec b;
    BEGIN b; END;
    ERROR at line 1:
    ORA-01476: divisor is equal to zero
    ORA-06512: at "SCOTT.B", line 9
    ORA-06512: at line 1
    SQL> select * from code_trace;
    TXT
    Procedure B's Declaration Section
    Procedure B's Statement Section
    Procedure A's Declaration Section
    Procedure A's Statement Section
    Procedure A's Exception Section
    Procedure B's Exception Section
    6 rows selected.
    SQL>
    Likewise, execution blocks can be nested deeper and deeper.
    5. How to continue exection of statements after an exception
    One of the common questions asked is how to return execution to the statement after the one that created the exception and continue on.
    Well, firstly, you can only do this for statements you expect to raise an exception, such as when you want to check if there is no data found in a query.
    If you consider what's been shown above you could put any statement you expect to cause an exception inside it's own procedure or function with it's own exception section to handle the exception without raising it back to the calling code.  However, the nature of procedures and functions is really to provide a means of re-using code, so if it's a statement you only use once it seems a little silly to go creating individual procedures for these.
    Instead, you nest execution blocks directly, to give the same result as shown in the diagram at the start of part 4 of this article.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure b (p_empno IN VARCHAR2) as
      2    v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
      3  begin
      4    v_dummy := log_trace('Procedure B''s Statement Section');
      5    -- Here we start another execution block nested in the first one...
      6    declare
      7      v_dummy NUMBER := log_trace('Nested Block Declaration Section');
      8    begin
      9      v_dummy := log_trace('Nested Block Statement Section');
    10      select empno
    11        into   v_dummy
    12        from   emp
    13       where  empno = p_empno; -- Note: the parameters and variables from
                                         parent execution block are available to use!
    14    exception
    15      when no_data_found then
    16        -- This is an exception we can handle so we don't raise it
    17        v_dummy := log_trace('No employee was found');
    18        v_dummy := log_trace('Nested Block Exception Section - Exception Handled');
    19      when others then
    20        -- Other exceptions we can't handle so we raise them
    21        v_dummy := log_trace('Nested Block Exception Section - Exception Raised');
    22        raise;
    23    end;
    24    -- ...Here endeth the nested execution block
    25    -- As the nested block handled it's exception we come back to here...
    26    v_dummy := log_trace('Procedure B''s Statement Section Continued');
    27  exception
    28    when others then
    29      -- We'll only get to here if an unhandled exception was raised
    30      -- either in the nested block or in procedure b's statement section
    31      v_dummy := log_trace('Procedure B''s Exception Section');
    32      raise;
    33* end;
    SQL> /
    Procedure created.
    SQL> exec b(123);
    PL/SQL procedure successfully completed.
    SQL> select * from code_trace;
    TXT
    Procedure B's Declaration Section
    Procedure B's Statement Section
    Nested Block Declaration Section
    Nested Block Statement Section
    No employee was found
    Nested Block Exception Section - Exception Handled
    Procedure B's Statement Section Continued
    7 rows selected.
    SQL> truncate table code_trace;
    Table truncated.
    SQL> exec b('ABC');
    BEGIN b('ABC'); END;
    ERROR at line 1:
    ORA-01722: invalid number
    ORA-06512: at "SCOTT.B", line 32
    ORA-06512: at line 1
    SQL> select * from code_trace;
    TXT
    Procedure B's Declaration Section
    Procedure B's Statement Section
    Nested Block Declaration Section
    Nested Block Statement Section
    Nested Block Exception Section - Exception Raised
    Procedure B's Exception Section
    6 rows selected.
    SQL>
    You can see from this that, very simply, the code that we expected may have an exception was able to either handle the exception and return to the outer execution block to continue execution, or if an unexpected exception occurred then it was able to be raised up to the outer exception section.
    6. User defined exceptions
    There are three sorts of 'User Defined' exceptions.  There are logical situations (e.g. business logic) where, for example, certain criteria are not met to complete a task, and there are existing Oracle errors that you wish to give a name to in order to capture them in the exception section.  The third is raising your own exception messages with our own exception numbers.  Let's look at the first one...
    Let's say I have tables which detail stock availablility and reorder levels...
    SQL> select * from reorder_level;
       ITEM_ID STOCK_LEVEL
             1          20
             2          20
             3          10
             4           2
             5           2
    SQL> select * from stock;
       ITEM_ID ITEM_DESC  STOCK_LEVEL
             1 Pencils             10
             2 Pens                 2
             3 Notepads            25
             4 Stapler              5
             5 Hole Punch           3
    SQL>
    Now, our Business has told the administrative clerk to check stock levels and re-order anything that is below the re-order level, but not to hold stock of more than 4 times the re-order level for any particular item.  As an IT department we've been asked to put together an application that will automatically produce the re-order documents upon the clerks request and, because our company is so tight-ar*ed about money, they don't want to waste any paper with incorrect printouts so we have to ensure the clerk can't order things they shouldn't.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6      from stock s join reorder_level r on (s.item_id = r.item_id)
      7      where s.item_id = p_item_id;
      8    --
      9    v_stock cur_stock_reorder%ROWTYPE;
    10  begin
    11    OPEN cur_stock_reorder;
    12    FETCH cur_stock_reorder INTO v_stock;
    13    IF cur_stock_reorder%NOTFOUND THEN
    14      RAISE no_data_found;
    15    END IF;
    16    CLOSE cur_stock_reorder;
    17    --
    18    IF v_stock.stock_level >= v_stock.reorder_level THEN
    19      -- Stock is not low enough to warrant an order
    20      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    21    ELSE
    22      IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    23        -- Required amount is over-ordering
    24        DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                     ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    25      ELSE
    26        DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    27        -- Here goes our code to print the order
    28      END IF;
    29    END IF;
    30    --
    31  exception
    32    WHEN no_data_found THEN
    33      CLOSE cur_stock_reorder;
    34      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    35* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(10,100);
    Invalid Item ID.
    PL/SQL procedure successfully completed.
    SQL> exec re_order(3,40);
    Stock has not reached re-order level yet!
    PL/SQL procedure successfully completed.
    SQL> exec re_order(1,100);
    Quantity specified is too much.  Max for this item: 70
    PL/SQL procedure successfully completed.
    SQL> exec re_order(2,50);
    Order OK.  Printing Order...
    PL/SQL procedure successfully completed.
    SQL>
    Ok, so that code works, but it's a bit messy with all those nested IF statements. Is there a cleaner way perhaps?  Wouldn't it be nice if we could set up our own exceptions...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6      from stock s join reorder_level r on (s.item_id = r.item_id)
      7      where s.item_id = p_item_id;
      8    --
      9    v_stock cur_stock_reorder%ROWTYPE;
    10    --
    11    -- Let's declare our own exceptions for business logic...
    12    exc_not_warranted EXCEPTION;
    13    exc_too_much      EXCEPTION;
    14  begin
    15    OPEN cur_stock_reorder;
    16    FETCH cur_stock_reorder INTO v_stock;
    17    IF cur_stock_reorder%NOTFOUND THEN
    18      RAISE no_data_found;
    19    END IF;
    20    CLOSE cur_stock_reorder;
    21    --
    22    IF v_stock.stock_level >= v_stock.reorder_level THEN
    23      -- Stock is not low enough to warrant an order
    24      RAISE exc_not_warranted;
    25    END IF;
    26    --
    27    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    28      -- Required amount is over-ordering
    29      RAISE exc_too_much;
    30    END IF;
    31    --
    32    DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    33    -- Here goes our code to print the order
    34    --
    35  exception
    36    WHEN no_data_found THEN
    37      CLOSE cur_stock_reorder;
    38      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    39    WHEN exc_not_warranted THEN
    40      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    41    WHEN exc_too_much THEN
    42      DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                  ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    43* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(10,100);
    Invalid Item ID.
    PL/SQL procedure successfully completed.
    SQL> exec re_order(3,40);
    Stock has not reached re-order level yet!
    PL/SQL procedure successfully completed.
    SQL> exec re_order(1,100);
    Quantity specified is too much.  Max for this item: 70
    PL/SQL procedure successfully completed.
    SQL> exec re_order(2,50);
    Order OK.  Printing Order...
    PL/SQL procedure successfully completed.
    SQL>
    That's better.  And now we don't have to use all those nested IF statements and worry about it accidently getting to code that will print the order out as, once one of our user defined exceptions is raised, execution goes from the Statements section into the Exception section and all handling of errors is done in one place.
    Now for the second sort of user defined exception...
    A new requirement has come in from the Finance department who want to have details shown on the order that show a re-order 'indicator' based on the formula ((maximum allowed stock - current stock)/re-order quantity), so this needs calculating and passing to the report...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6            ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
      7      from stock s join reorder_level r on (s.item_id = r.item_id)
      8      where s.item_id = p_item_id;
      9    --
    10    v_stock cur_stock_reorder%ROWTYPE;
    11    --
    12    -- Let's declare our own exceptions for business logic...
    13    exc_not_warranted EXCEPTION;
    14    exc_too_much      EXCEPTION;
    15  begin
    16    OPEN cur_stock_reorder;
    17    FETCH cur_stock_reorder INTO v_stock;
    18    IF cur_stock_reorder%NOTFOUND THEN
    19      RAISE no_data_found;
    20    END IF;
    21    CLOSE cur_stock_reorder;
    22    --
    23    IF v_stock.stock_level >= v_stock.reorder_level THEN
    24      -- Stock is not low enough to warrant an order
    25      RAISE exc_not_warranted;
    26    END IF;
    27    --
    28    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    29      -- Required amount is over-ordering
    30      RAISE exc_too_much;
    31    END IF;
    32    --
    33    DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    34    -- Here goes our code to print the order, passing the finance_factor
    35    --
    36  exception
    37    WHEN no_data_found THEN
    38      CLOSE cur_stock_reorder;
    39      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    40    WHEN exc_not_warranted THEN
    41      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    42    WHEN exc_too_much THEN
    43      DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                  ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    44* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(2,40);
    Order OK.  Printing Order...
    PL/SQL procedure successfully completed.
    SQL> exec re_order(2,0);
    BEGIN re_order(2,0); END;
    ERROR at line 1:
    ORA-01476: divisor is equal to zero
    ORA-06512: at "SCOTT.RE_ORDER", line 17
    ORA-06512: at line 1
    SQL>
    Hmm, there's a problem if the person specifies a re-order quantity of zero.  It raises an unhandled exception.
    Well, we could put a condition/check into our code to make sure the parameter is not zero, but again we would be wrapping our code in an IF statement and not dealing with the exception in the exception handler.
    We could do as we did before and just include a simple IF statement to check the value and raise our own user defined exception but, in this instance the error is standard Oracle error (ORA-01476) so we should be able to capture it inside the exception handler anyway... however...
    EXCEPTION
      WHEN ORA-01476 THEN
    ... is not valid.  What we need is to give this Oracle error a name.
    This is done by declaring a user defined exception as we did before and then associating that name with the error number using the PRAGMA EXCEPTION_INIT statement in the declaration section.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6            ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
      7      from stock s join reorder_level r on (s.item_id = r.item_id)
      8      where s.item_id = p_item_id;
      9    --
    10    v_stock cur_stock_reorder%ROWTYPE;
    11    --
    12    -- Let's declare our own exceptions for business logic...
    13    exc_not_warranted EXCEPTION;
    14    exc_too_much      EXCEPTION;
    15    --
    16    exc_zero_quantity EXCEPTION;
    17    PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
    18  begin
    19    OPEN cur_stock_reorder;
    20    FETCH cur_stock_reorder INTO v_stock;
    21    IF cur_stock_reorder%NOTFOUND THEN
    22      RAISE no_data_found;
    23    END IF;
    24    CLOSE cur_stock_reorder;
    25    --
    26    IF v_stock.stock_level >= v_stock.reorder_level THEN
    27      -- Stock is not low enough to warrant an order
    28      RAISE exc_not_warranted;
    29    END IF;
    30    --
    31    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    32      -- Required amount is over-ordering
    33      RAISE exc_too_much;
    34    END IF;
    35    --
    36    DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    37    -- Here goes our code to print the order, passing the finance_factor
    38    --
    39  exception
    40    WHEN exc_zero_quantity THEN
    41      DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
    42    WHEN no_data_found THEN
    43      CLOSE cur_stock_reorder;
    44      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    45    WHEN exc_not_warranted THEN
    46      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    47    WHEN exc_too_much THEN
    48      DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                  ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    49* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(2,0);
    Quantity of 0 (zero) is invalid.
    PL/SQL procedure successfully completed.
    SQL>
    Lastly, let's look at raising our own exceptions with our own exception numbers...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6            ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
      7      from stock s join reorder_level r on (s.item_id = r.item_id)
      8      where s.item_id = p_item_id;
      9    --
    10    v_stock cur_stock_reorder%ROWTYPE;
    11    --
    12    exc_zero_quantity EXCEPTION;
    13    PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
    14  begin
    15    OPEN cur_stock_reorder;
    16    FETCH cur_stock_reorder INTO v_stock;
    17    IF cur_stock_reorder%NOTFOUND THEN
    18      RAISE no_data_found;
    19    END IF;
    20    CLOSE cur_stock_reorder;
    21    --
    22    IF v_stock.stock_level >= v_stock.reorder_level THEN
    23      -- Stock is not low enough to warrant an order
    24      [b]RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached re-order level yet!');[/b]
    25    END IF;
    26    --
    27    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    28      -- Required amount is over-ordering
    29     

    its nice article, have put up this one the blog
    site,Nah, I don't have time to blog, but if one of the other Ace's/Experts wants to copy it to a blog with reference back to here (and all due credit given ;)) then that's fine by me.
    I'd go for a book like "Selected articles by OTN members" or something. Does anybody have a list of links of all those mentioned articles?Just these ones I've bookmarked...
    Introduction to regular expressions ... by CD
    When your query takes too long ... by Rob van Wijk
    How to pipeline a function with a dynamic number of columns? by ascheffer
    PL/SQL 101 : Exception Handling by BluShadow

  • Delete Statement Exception Handling

    Hi guys,
    I have a problem in my procedure. There are 3 parameters that I am passing into the procedure. I am matching these parameters to those in the table to delete one record at a time.
    For example if I would like to delete the record with the values ('900682',3,'29-JUL-2008') as parameters, it deletes the record from the table but then again when I execute it with the same parameters it should show me an error message but it again says 'Deleted the Transcript Request.....' Can you please help me with this?
    PROCEDURE p_delete_szptpsr_1 (p_shttran_id IN saturn.shttran.shttran_id%TYPE,
    p_shttran_seq_no IN saturn.shttran.shttran_seq_no%TYPE,
    p_shttran_request_date IN saturn.shttran.shttran_request_date%TYPE) IS
    BEGIN
    DELETE FROM saturn.shttran
    WHERE shttran.shttran_id = p_shttran_id
    and shttran.shttran_seq_no = p_shttran_seq_no
    and trunc(shttran_request_date) = trunc(p_shttran_request_date);
    DBMS_OUTPUT.PUT_LINE('Deleted the Transcript Request Seq No (' || p_shttran_seq_no || ') of the Student (' || p_shttran_id ||') for the requested date of (' || p_shttran_request_date ||')');
    COMMIT;
    EXCEPTION WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('Error: The supplied Notre Dame Student ID = (' || p_shttran_id ||
    '), Transcript Request No = (' || p_shttran_seq_no || '), Request Date = (' || p_shttran_request_date || ') was not found.');
    END p_delete_szptpsr_1;
    Should I have a SELECT statement to use NO_DATA_FOUND ???

    A DELETE statement that deletes no rows (just like an UPDATE statement that updates no rows) is not an error to Oracle. Oracle won't throw any exception.
    If you want your code to throw an exception, you'll need to write that logic. You could throw a NO_DATA_FOUND exception yourself, i.e.
    IF( SQL%ROWCOUNT = 0 )
    THEN
      RAISE no_data_found;
    END IF;If you are just going to catch the exception, though, you could just embed whatever code you would use to handle the exception in your IF statement, i.e.
    IF( SQL%ROWCOUNT = 0 )
    THEN
      <<do something about the exception>>
    END IF;In your original code, your exception handler is just a DBMS_OUTPUT statement. That is incredibly dangerous in real production code. You are relying on the fact that the client has enabled output, that the client has allocated a large enough buffer, that the user is going to see the message, and that the procedure will never be called from any piece of code that would ever care if it succeeded or failed. There are vanishingly few situations where those are safe things to rely on.
    Justin

  • Exception handling is not working in GCC compile shared object

    Hello,
    I am facing very strange issue on Solaris x86_64 platform with C++ code compiled usging gcc.3.4.3.
    I have compiled shared object that load into web server process space while initialization. Whenever any exception generate in code base, it is not being caught by exception handler. Even though exception handlers are there. Same code is working fine since long time but on Solaris x86, Sparc arch, Linux platform
    With Dbx, I am getting following stack trace.
    Stack trace is
    dbx: internal error: reference through NULL pointer at line 973 in file symbol.cc
    [1] 0x11335(0x1, 0x1, 0x474e5543432b2b00, 0x59cb60, 0xfffffd7fffdff2b0, 0x11335), at 0x11335
    ---- hidden frames, use 'where -h' to see them all ----
    =>[4] __cxa_throw(obj = (nil), tinfo = (nil), dest = (nil), , line 75 in "eh_throw.cc"
    [5] OBWebGate_Authent(r = 0xfffffd7fff3fb300), line 86 in "apache.cpp"
    [6] ap_run_post_config(0x0, 0x0, 0x0, 0x0, 0x0, 0x0), at 0x444624
    [7] main(0x0, 0x0, 0x0, 0x0, 0x0, 0x0), at 0x42c39a
    I am using following link options.
    Compile option is
    /usr/sfw/bin/g++ -c -I/scratch/ashishas/view_storage/build/coreid1014/palantir/apache22/solaris-x86_64/include -m64 -fPIC -D_REENTRANT -Wall -g -o apache.o apache.cpp
    Link option is
    /usr/sfw/bin/g++ -shared -m64 -o apache.so apache.o -lsocket -lnsl -ldl -lpthread -lthread
    At line 86, we are just throwing simple exception which have catch handlers in place. Also we do have catch(...) handler as well.
    Surpursing things are..same issue didn't observe if we make it as executable.
    Issue only comes if this is shared object loaded on webserver. If this is plain shared object, opened by anyother exe, it works fine.
    Can someone help me out. This is completly blocking issue for us. Using Solaris Sun Studio compiler is no option as of now.

    shared object that load into web server process space
    ... same issue didn't observe if we make it as executable.When you "inject" your shared object into some other process a well-being of your exception handling depends on that other process.
    Mechanics of x64 stack traversing (unwind) performed when you throw the exception is quite complicated,
    particularly involving a "nearly-standartized" Unwind interface (say, Unwind_RaiseException).
    When we are talking about g++ on Solaris there are two implementations of unwind interface, one in libc and one in libgcc_s.so.
    When you g++-compile the executable you get it directly linked with libgcc_s.so and Unwind stuff resolves into libgccs.
    When g++-compiled shared object is loaded into non-g++-compiled executable's process _Unwind calls are most likely already resolved into Solaris libc.
    Thats why you might see the difference.
    Now, what exactly causes this difference can vary, I can only speculate.
    All that would not be a problem if _Unwind interface was completely standartized and properly implemented.
    However there are two issues currently:
    * gcc (libstdc++ in particular) happens to use additional non-standard _Unwind calls which are not present in Solaris libc
    naturally, implementation details of Unwind implementation in libc differs to that of libgccs, so when all the standard _Unwind
    routines are resolved into Solaris version and one non-standard _Unwind routine is resolved into gcc version you get a problem
    (most likely that is what happens with you)
    * libc Unwind sometimes is unable to decipher the code generated by gcc.
    However that is likely to happen with modern gcc (say, 4.4+) and not that likely with 3.4.3
    Btw, you can check your call frame to see where _Unwind calls come from:
    where -h -lIf you indeed stomped on "mixed _Unwind" problem then the only chance for you is to play with linker
    so it binds Unwind stuff from your library directly into libgccs.
    Not tried it myself though.
    regards,
    __Fedor.

  • Exception handling to catch the outcome of a select

    Hello,
    I want to use exception handling to exit me out of a function module.  I want to have one exception for all errors.
    For example, if this select statement does not work, how do I finish up this code to make it work.
    error type cx_bsx
    try
    select * from t001 where BUKRS = '!@#$'
    catch <not sure what> into INTO error
    raise exception error
    endtry.
    When I use cx_bsx with the catch, nothing happens even though the select statement fails. Basically I want the catch to work in the same manner as this:
    if sy-subrc ne 0.
    raise error_table_read.
    endif.

    If this code is in a function module, then why not just use the function  module exceptions.
    if sy-subrc ne 0.
    raise error_table_read.
    endif.
    What are you gaining by "catching" this exception in the function module.  By using the "exceptions" part of the function module, you are passing this exception back to the calling program.
    Regards,
    Rich Heilman

  • Throwing Exception having multiple arguments in constructor

    hi,
    I am trying to implement exception handling for a JAVA + C++ module.
    In which C++ exception is caught by a Java module.
    The c++ code is as follows,
    try
    ///////////===========
    } catch (Exception1 &e) {
    jclass clazz = jenv->FindClass("test/Exception1Java");
    if(clazz)
    jenv->ThrowNew(clazz,e.getErrMsg().c_str());
    return 0;
    } catch (Exception2 &e) {
    jclass clazz = jenv->FindClass("test/Exception2");
    if(clazz)
    jenv->ThrowNew(clazz,e.getErrMsg().c_str());
    return 0;
    This works perfectly fine.
    But I want to pass one more argument as int while throwing the java exception.
    jenv->ThrowNew(clazz,e.getErrId(),e.getErrMsg().c_str());
    As the jenv->ThrowNew function only take two arguments I am unable to send the error id( int ) to the message.
    Is there any alternate to this function or some other approach to throw the java exceptions.

    hi,
    I am trying to implement exception handling for a
    JAVA + C++ module.
    In which C++ exception is caught by a Java module.
    The c++ code is as follows,<snip>
    >
    But I want to pass one more argument as int while
    throwing the java exception.
    env->ThrowNew(clazz,e.getErrId(),e.getErrMsg().c_str());>
    As the jenv->ThrowNew function only take two
    arguments I am unable to send the error id( int ) to
    the message.
    Is there any alternate to this function or some other
    approach to throw the java exceptions.Build the exception using the normal FindClass, GetMethodID approach,. and then throw it.
    #include "NativeExceptionTest.h"
    JNIEXPORT void JNICALL Java_NativeExceptionTest_test
    (JNIEnv *env, jobject obj, jint data) {
         if (data == 42) {
              jclass excClass = env->FindClass("MyException");
              if (!excClass) {
                   return;
              jmethodID ctorID = env->GetMethodID(excClass, "<init>", "(ILjava/lang/String;)V");
              if (!ctorID) {
                   return;
              jstring excMessage = env->NewStringUTF("ILLEGAL VALUE");
              jobject excObject = env->NewObject(excClass, ctorID,-1,excMessage);
              if (!excObject) {
                   return;
              env->Throw((jthrowable)excObject);
         return;
    }============================================
    public class NativeExceptionTest {
         static {
              System.loadLibrary("nativeException");
         NativeExceptionTest() {
               try {
                    test(42);
               } catch (MyException e) {
                   System.out.println("Exception: " + e.getCode() + "(" + e.getMessage() +")");
         private native void test(int i) throws MyException;
         public static void main(String[] args) {
              new NativeExceptionTest();
    class MyException extends Exception {
         private int code;
         MyException(int code, String message) {
              super(message);
              this.code = code;
         int getCode() {
              return this.code;
    }

  • Exception handling for all the insert statements in the proc

    CREATE PROCEDURE TEST (
    @IncrStartDate DATE
    ,@IncrEndDate DATE
    ,@SourceRowCount INT OUTPUT
    ,@TargetRowCount INT OUTPUT
    ,@ErrorNumber INT OUTPUT
    ,@ErrorMessage VARCHAR(4000) OUTPUT
    ,@InsertCase INT --INSERT CASE INPUT
    WITH
    EXEC AS CALLER AS
    BEGIN --Main Begin
    SET NOCOUNT ON
    BEGIN TRY
    DECLARE @SuccessNumber INT = 0
    ,@SuccessMessage VARCHAR(100) = 'SUCCESS'
    ,@BenchMarkLoadFlag CHAR(1)
    ,@BenchmarkFlow INT
    ,@MonthYearStart DATE
    ,@MonthYearEnd DATE
    ,@StartDate DATE
    ,@EndDate DATE
    /* Setting the default values of output parameters to 0.*/
    SET @SourceRowCount = 0
    SET @TargetRowCount = 0
    /*Setting the Start and end date for looping */
    SET @MonthYearStart = @IncrStartDate;
    SET @MonthYearEnd = @IncrEndDate;
    /* Setting the @InsertCase will ensure case wise insertion as this sp will load data in different tables
    @InsertCase =0 means data will be inserted in the target TAB1
    @InsertCase =1 means data will be inserted in the target TAB2
    @InsertCase =2 means data will be inserted in the target TAB3
    @InsertCase =3 means data will be inserted in the target TAB4
    @InsertCase =4 means data will be inserted in the target TAB5
    @InsertCase =5 means data will be inserted in the target TAB6
    if @InsertCase =0
    WHILE (@MonthYearStart <= @MonthYearEnd)
    BEGIN
    SET @StartDate = @MonthYearStart;
    SET @EndDate = @MonthYearEnd;
    /* Delete from target where date range given from input parameter*/
    DELETE FROM TAB1
    WHERE [MONTH] BETWEEN MONTH(@StartDate) AND MONTH(@EndDate)
    AND [YEAR] BETWEEN year(@StartDate) and year(@EndDate)
    /*Insert data in target-TAB1 */
    BEGIN TRANSACTION
    INSERT INTO TAB1
    A,B,C
    SELECT
    A,BC
    FROM XYZ
    COMMIT TRANSACTION
    SET @MonthYearStart = DATEADD(MONTH, 1, @MonthYearStart)
    SELECT @TargetRowCount = @TargetRowCount + @@ROWCOUNT;
    END -- End of whileloop
    END TRY
    BEGIN CATCH
    IF @@TRANCOUNT>0
    ROLLBACK TRANSACTION
    SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE();
    END CATCH
    END--End of Main Begin
    I have the above proc inserting data based on parameters  where in @InsertCase  is used for case wise execution.
     I have written the whole proc with exception handling using try catch block.
    I have just added one insert statement here for 1 case  now I need to add further insert  cases
    INSERT INTO TAB4
                    A,B,C
    SELECT
                                    A,BC
    FROM XYZ
    INSERT INTO TAB3
                    A,B,C
    SELECT
                                    A,BC
    FROM XYZ
    INSERT INTO TAB2
                    A,B,C
    SELECT
                                    A,BC
    FROM XYZ
    I will be using following to insert further insert statements 
    if @InsertCase =1 
    I just needed to know where will be my next insert statement should be fitting int his code so that i cover exception handling for all the code
    Mudassar

    Hi Erland & Mudassar, I have attempted to recreate Mudassar's original problem..here is my TABLE script;
    USE [MSDNTSQL]
    GO
    /****** Object: Table [dbo].[TAB1] Script Date: 2/5/2014 7:47:48 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[TAB1](
    [COL1] [nvarchar](1) NULL,
    [COL2] [nvarchar](1) NULL,
    [COL3] [nvarchar](1) NULL,
    [START_MONTH] [int] NULL,
    [END_MONTH] [int] NULL,
    [START_YEAR] [int] NULL,
    [END_YEAR] [int] NULL
    ) ON [PRIMARY]
    GO
    Then here is a CREATE script for the SPROC..;
    USE [MSDNTSQL]
    GO
    /****** Object: StoredProcedure [dbo].[TryCatchTransactions1] Script Date: 2/5/2014 7:51:33 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE PROCEDURE [dbo].[TryCatchTransactions1] (
    @IncrStartDate DATE
    ,@IncrEndDate DATE
    ,@SourceRowCount INT OUTPUT
    ,@TargetRowCount INT OUTPUT
    ,@ErrorNumber INT OUTPUT
    ,@ErrorMessage VARCHAR(4000) OUTPUT
    ,@InsertCase INT --INSERT CASE INPUT
    WITH
    EXEC AS CALLER AS
    BEGIN --Main Begin
    SET NOCOUNT ON
    BEGIN TRY
    DECLARE @SuccessNumber INT = 0
    ,@SuccessMessage VARCHAR(100) = 'SUCCESS'
    ,@BenchMarkLoadFlag CHAR(1)
    ,@BenchmarkFlow INT
    ,@MonthYearStart DATE
    ,@MonthYearEnd DATE
    ,@StartDate DATE
    ,@EndDate DATE
    /* Setting the default values of output parameters to 0.*/
    SET @SourceRowCount = 0
    SET @TargetRowCount = 0
    /*Setting the Start and end date for looping */
    SET @MonthYearStart = @IncrStartDate;
    SET @MonthYearEnd = @IncrEndDate;
    /* Setting the @InsertCase will ensure case wise insertion as this sp will load data in different tables
    @InsertCase =0 means data will be inserted in the target TAB1
    @InsertCase =1 means data will be inserted in the target TAB2
    @InsertCase =2 means data will be inserted in the target TAB3
    @InsertCase =3 means data will be inserted in the target TAB4
    @InsertCase =4 means data will be inserted in the target TAB5
    @InsertCase =5 means data will be inserted in the target TAB6
    IF @InsertCase =0
    WHILE (@MonthYearStart <= @MonthYearEnd)
    BEGIN
    SET @StartDate = @MonthYearStart;
    SET @EndDate = @MonthYearEnd;
    /* Delete from target where date range given from input parameter*/
    DELETE FROM TAB1
    WHERE START_MONTH BETWEEN MONTH(@StartDate) AND MONTH(@EndDate)
    AND START_YEAR BETWEEN year(@StartDate) and YEAR(@EndDate)
    /*Insert data in target-TAB1 */
    BEGIN TRANSACTION
    INSERT INTO TAB1 (COL1,COL2,COL3)
    VALUES ('Z','X','Y')
    SELECT COL1, COL2, COL3
    FROM TAB1
    COMMIT TRANSACTION
    SET @MonthYearStart = DATEADD(MONTH, 1, @MonthYearStart)
    SELECT @TargetRowCount = @TargetRowCount + @@ROWCOUNT;
    END -- End of whileloop
    END TRY
    BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
    SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE();
    END CATCH
    PRINT @SUCCESSMESSAGE
    END--End of Main Begin
    GO
    I am just trying to help --danny rosales
    UML, then code

Maybe you are looking for

  • Is this a Weblogic bug?

    Hi all, Please help....I really don't know what to do with this problem as have try all methods that I know of... I suspect is this a Welogic bug? It happens intermittently too..... Need help on this weird exception i have. My stateless session EJB a

  • ERROR B191 - IDoc has its own logical system as receiver

    I everybody, i'm tryng to execute a package to charge a ODS from another ODS (Datamart) but the process ends with the error "IDoc has its own logical system as receiver", can you help me with is? What should be the reason for this error? What can i m

  • No picture when exporting

    i have a project made up of avi (optimized) (codec CineForm HD) + apple prores422 files. the first time i exported the project i was having some trouble but somehow was able to succesfully manage. exported onto vimeo+master file. now, after making a

  • Can anyone suggest me the OBIEE Repository/Answers best practice document?

    Hi, I'm looking for the OBIEE repository/answers/dashboard development best practice doument.can you suggest me where can i find this document?

  • How can i change VBAK-Faksk of VAO1 at header level using BAPI_SALESORD_CHA

    Hi Experts, How can i change the value of VBAK-FAKSK (Billing doc value) at header level . by using the bapi_salesorder_change.Could you please send the sample code how to change the value of any field in VBAk . so that i can take as reference and wo