Exception handling in Swing Gui

I have an app with a (class) structure sort of like this:
Application
.contains JFrame
..contains 'View'
...contains JTable
....'contains' TableModel
Among other things but that's the important bits here.
When I update a field in the table the setValueAt method in the TableModel is called and updates a database via JDBC. This all works fine as long as everything goes well, but if there's an SQLException , I'd like to pop up a modal errordialog with the exception message. Question is, how do I do that best? It would of course be preferable to have a catch somewhere higher up that above chain but from what I've seen while searching the archives, it's not an easy thing to do that in a gui (Event dispatching thread voodoo or something) so I might have to do try and catch in the tablemodels for each different table? If so, how do the tablemodels get hold of the JFrame object so they can pass it to the dialog to make it modal? Right now I'm passing the JFrame to the Views, which pass them to their Tables, which pass them to the TableModels etc etc and it seems like there should be a more elegant way of doing this.

Since only the logic of the TableModel can generate the exceptions, there's no way to catch them at the JTable, I don't think.
If your TableModel "knows about" its JTable, how about something like:
  JTable myTbl = theModel.getMyTable();
  Container p = myTbl.getParent();
  while (p != null && !(p instanceof Frame)) {
    p = p.getParent();
  if (p instanceof Frame) {
    JDialog dlg = new JDialog(p, "SQL ERROR!", true);
  } else {
     * OW!  How can we NOT be in a containment hierarchy?
     * Do something appropriately drastic here...
  }Whether you do the "upwards crawl" every time you catch an exception, at create-time, or once and then cache, is an optimization that depends on how often you expect to hit errors.
Another option is to have your TableModel implement an "ExceptionListenerList", kinda like the TableModelListener. Then you could have more than one entity listening for the exceptions you're hitting. Somewhat more elegant than having the model know about a single owner.

Similar Messages

  • Centralized exception handling

    http://www.artima.com/intv/handcuffs2.html
    The above is a text concerning the C# language. It contains some viewpoints concerning exceptions, and I want to lift one concept out of the text: Centralized exception handling
    I want to implement some kind of centralized exception handling in a gui application (swt, but that's not really relevant). Could you give a 1 mile high overview of what you do? How do you log the exceptions for later investigation by developers? How do you internationalize/localize error messages toward the user? Logically, where do you place this centralized exception handler? Before the statemachine, after it, in the messageloop, in one kind of messageloop but not in others, or 'it depends'? Is there a library that attempts to simplify this? If you have a centralized exception handler, how do you decide what errors are worth displaying a humand readable text for, and for what others you maybe prepare a dump with the stacktrace, all available context data, etc? What are your best practices? What would you recommend to avoid?

    Expanding on this: http://www.artima.com/intv/solid2.html

  • Environment.Exit hangs when called from an application domain exception handler

    I've implemented a handler for exceptions not thrown in the main GUI thread of my C# WinForms application, as follows:
        AppDomain.CurrentDomain.UnhandledException  += OnUnhandledExceptionThrown;
    This handler is called from a background thread. The last statement in this handler is a call to
    Environment.Exit with the application exit code. However, the application hangs in this call. From within Visual Studio, it hangs and I'm unable to break the application; I have to use Task Manager to terminate Visual Studio. Environment.Exit
    works fine when called from the unhandled exception handler for the GUI thread. Is there a better way to terminate the application in the context of an unhandled exception thrown by a background thread?

    Are you just trying to avoid a crash? Environment.Exit can cause deadlocking if exiting in the wrong kind of scenario; if you're just trying to avoid a crash, use
    GetCurrentProcess with
    TerminateProcess to terminate your own process.  It skips the notification phases that Environment.Exit uses which prevents the common deadlock scenarios.
    WinSDK Support Team Blog: http://blogs.msdn.com/b/winsdk/

  • Exception Handling with GUI

    Hi,
    I'm new to Java so I'm a little rusty with exception handling. Please help me with this portion of my code. I'm supposed to screen out the bad input by the user. The user has to enter a double value and not an illegal value, for example: 45ab would be unacceptable. I've tried this way but after entering a number, the program just exits. Thanks first for helping me out.
    import javax.swing.*;
    import java.io.*;
    import java.text.*;
    public class Circle {
    public static double readDouble() {
    boolean done = false;
    String s;
    double d=0;
    while (!done) {
    JOptionPane.showInputDialog("Enter a double : ");
    System.out.flush();
    try {
    BufferedReader in = new BufferedReader (
    new InputStreamReader(System.in));
    s = in.readLine();
    d = Double.parseDouble(s);
    d = new Double(s).doubleValue();
    done = true;
    }catch (IOException e){
    done = true;
    }catch (NumberFormatException e1){
    JOptionPane.showMessageDialog(null,"Error -- input a double -- Try again");
    return d;
    public static void area(){
    double radius1;
    double area;
    radius1 = readDouble();
    area = (radius1 * radius1) * Math.PI;
    // Rounding the area value to 2 decimal places
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);
    JOptionPane.showMessageDialog(null, "The area is " + nf.format(area));
    // There are more code after this.

    Hello, I quickly wrote a possible solution to your problem, hope it will help you. (ICQ #28985387)
    import javax.swing.*;
    public class InputExample {
    public static double getDouble() {
    String input;
    do {
    input = JOptionPane.showInputDialog(null, "Enter a double", "Input", JOptionPane.QUESTION_MESSAGE);
    } while(!validateDouble(input));
    return Double.parseDouble(input);
    private static boolean validateDouble(String input) {
    double num = 0;
    try {
    if(input.length() == 0) {
    JOptionPane.showMessageDialog(null, "Please enter a value", "Warning", JOptionPane.WARNING_MESSAGE);
    return false;
    num = Double.parseDouble(input);
    } catch(NullPointerException exception) {
    System.exit(0);
    } catch(NumberFormatException exception) {
    JOptionPane.showMessageDialog(null, "Not a double", "Warning", JOptionPane.WARNING_MESSAGE);
    return false;
    if (num < -Double.MAX_VALUE || Double.MAX_VALUE < num) {
    JOptionPane.showMessageDialog(null, "Must be between\n" + (-Double.MAX_VALUE) + "\nand " + Double.MAX_VALUE, "Warning", JOptionPane.WARNING_MESSAGE);
    return false;
    return true;
    }

  • Multi-Client TCP Server /w Swing GUI

    Hi everybody,
    i have to develop a Multi-Client TCP Server with a Swing GUI. The GUI mainly consists of a JTable which shows various trace messages from processes running on other computers. As the data needs to be filtered i�m using a custom TableModel derived from AbstractTableModel. I�m creating a new thread for every client that connects as shown in http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.html
    Now every client thread reads data from its TCP connection and puts it into the JTable by calling the method addRow of the model. But i�m getting strange NullPointerExceptions and IndexOutOfBoundExceptions when data arrives (i�m using ArrayList in the model). These exceptions never show in a single-threaded Swing app (i�ve tested this already, so i don�t think it�s a bug in my model), so i think this is a problem with Swing�s thread unsafety? Do you have any hints on how to get away with it? Also general design tips for a Multi-Client TCP Server /w Swing GUI are greatly appreciated.
    Thanks in advance!
    Best regards,
    Disposable_Hero

    Of course, but i don�t think it is the model (as said before it works fine in a single thread swing app)
    Here�s the code:
    public class LogTableModel extends AbstractTableModel{
    private Vector dataVector;
    private Vector filterVector;
    private String[] columnIdentifiers;
    private Vector filteredbyProcess;
    private Vector filteredbyLoglevel;
    private boolean bEnableRefresh;
    /** Creates a new instance of LogTableModel */
    public LogTableModel() {
    dataVector=new Vector(0);
    columnIdentifiers=new String[]{"LogTime","HostName","IP","ProcessName","LogLevel","Handle","PID","TID","LogData"};
    filteredbyProcess=new Vector(0);
    filteredbyLoglevel=new Vector(0);
    filterVector=new Vector(0);
    bEnableRefresh=true;
    public synchronized void enableRefresh(boolean bEnableRefresh){
    this.bEnableRefresh=bEnableRefresh;
    if(bEnableRefresh){
    this.buildIndexListBasedOnFilter();
    public synchronized void addRow(LogLine row){
    dataVector.add(row);
    if(bEnableRefresh)
    this.buildIndexListBasedOnFilter();
    public synchronized void addFilter(Filter filter){
    filterVector.add(filter);
    if(filter.isActive())
    this.buildIndexListBasedOnFilter();
    public synchronized void setFilterActive(String name,boolean active){
    int i;
    for(i=0;i<filterVector.size();i++)
    if(((Filter)filterVector.elementAt(i)).getName().equals(name))
    break;
    Filter tmp=(Filter)filterVector.elementAt(i);
    tmp.setActive(active);
    if(active)
    this.buildIndexListBasedOnFilter();
    public synchronized void setFilterLoglevel(String name,int Loglevel){
    int i;
    for(i=0;i<filterVector.size();i++)
    if(((Filter)filterVector.elementAt(i)).getName().equals(name))
    break;
    Filter tmp=(Filter)filterVector.elementAt(i);
    tmp.setLoglevel(Loglevel);
    if(tmp.isActive()==false)
    this.buildIndexListBasedOnFilter();
    private void buildIndexListBasedOnFilter(){
    filteredbyProcess.clear();
    filteredbyLoglevel.clear();
    applyProcessFilter();
    applyLoglevelFilter();
    if(bEnableRefresh)
    this.fireTableDataChanged();
    private void applyProcessFilter(){
    LogLine line=null;
    Filter filter=null;
    for(int i=0;i<dataVector.size();i++){
    for(int j=0;j<filterVector.size();j++){
    filter=(Filter)filterVector.elementAt(j);
    line=(LogLine)dataVector.elementAt(i);
    if(filter.isActive()&&(filter.getName().equals(line.getProcessName()))){
    line.setHidden(true);
    break;
    else{
    line.setHidden(false);
    if(line.getHidden()!=true)
    filteredbyProcess.add(new Integer(i));
    private void applyLoglevelFilter(){
    for(int i=0;i<filteredbyProcess.size();i++){
    int index=((Integer)filteredbyProcess.get(i)).intValue();
    LogLine line=(LogLine)dataVector.elementAt(index);
    for(int j=0;j<filterVector.size();j++){
    if(((Filter)filterVector.elementAt(j)).getName().equals(line.getProcessName())){
    Filter filter=(Filter)filterVector.elementAt(j);
    if((filter.getLoglevel()&line.getLogLevelAsInt())!=line.getLogLevelAsInt())
    line.setHidden(true);
    else
    filteredbyLoglevel.add(new Integer(index));
    break;
    public synchronized String getColumnName(int columnIndex){
    return columnIdentifiers[columnIndex];
    public synchronized void clearData(){
    dataVector.clear();
    filteredbyProcess.clear();
    filteredbyLoglevel.clear();
    public synchronized int getColumnCount() {
    return columnIdentifiers.length;
    public synchronized int getRowCount() {
    return filteredbyLoglevel.size();
    public synchronized Object getValueAt(int rowIndex, int columnIndex) {
    int iIndex=((Integer)filteredbyLoglevel.get(rowIndex)).intValue();// hier krachts warum???
    LogLine tmp=(LogLine)dataVector.elementAt(iIndex);
    switch(columnIndex){
    case 0:
    return tmp.getLogTime();
    case 1:
    return tmp.getHostName();
    case 2:
    return tmp.getIP();
    case 3:
    return tmp.getProcessName();
    case 4:
    return tmp.getLogLevel();
    case 5:
    return tmp.getHandle();
    case 6:
    return tmp.getProcessID();
    case 7:
    return tmp.getThreadID();
    case 8:
    return tmp.getLogData();
    default:
    return null;

  • Loading large files in Java Swing GUI

    Hello Everyone!
    I am trying to load large files(more then 70 MB of xml text) in a Java Swing GUI. I tried several approaches,
    1)Byte based loading whith a loop similar to
    pane.setText("");
                 InputStream file_reader = new BufferedInputStream(new FileInputStream
                           (file));
                 int BUFFER_SIZE = 4096;
                 byte[] buffer = new byte[BUFFER_SIZE];
                 int bytesRead;
                 String line;
                 while ((bytesRead = file_reader.read(buffer, 0, BUFFER_SIZE)) != -1)
                      line = new String(buffer, 0, bytesRead);
                      pane.append(line);
                 }But this is gives me unacceptable response times for large files and runs out of Java Heap memory.
    2) I read in several places that I could load only small chunks of the file at a time and when the user scrolls upwards or downwards the next/previous chunk is loaded , to achieve this I am guessing extensive manipulation for the ScrollBar in the JScrollPane will be needed or adding an external JScrollBar perhaps? Can anyone provide sample code for that approach? (Putting in mind that I am writting code for an editor so I will be needing to interact via clicks and mouse wheel roatation and keyboard buttons and so on...)
    If anyone can help me, post sample code or point me to useful links that deal with this issue or with writting code for editors in general I would be very grateful.
    Thank you in advance.

    Hi,
    I'm replying to your question from another thread.
    To handle large files I used the new IO libary. I'm trying to remember off the top of my head but the classes involved were the RandomAccessFile, FileChannel and MappedByteBuffer. The MappedByteBuffer was the best way for me to read and write to the file.
    When opening the file I had to scan through the contents of the file using a swing worker thread and progress monitor. Whilst doing this I indexed the file into managable chunks. I also created a cache to further optimise file access.
    In all it worked really well and I was suprised by the performance of the new IO libraries. I remember loading 1GB files and whilst having to wait a few seconds to perform the indexing you wouldn't know that the data for the JList was being retrieved from a file whilst the application was running.
    Good Luck,
    Martin.

  • JRE7: Exception Handler no longer works

    Hello Folks,
    in a large-scale Swing App (usually started via JWS) we used to define a global event handler by setting the "sun.awt.exception.handler" environment variable. This used to work under JRE6, but it doesn't work under JRE7 anymore. What is the replacement?
    Regards from Germany,
    Thomas Nagel

    http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.UncaughtExceptionHandler.html
    ?

  • Need help with threading in Swing GUI !!!

    I've written an app that parses and writes
    files. I'm using a Swing GUI. The app
    could potenially be used to parse hundreds or even
    thousands of files. I've included a JProgressBar
    to monitor progress. The problem is when I parse
    a large number of files the GUI freezes and only
    updates the values of the progress bar when the
    parsing and writing process is finished.
    I assume I need to start the process in a seperate thread. But, I'm new to threads and I'm not sure
    whether to start the Progressbar code in a seperate
    thread or the parsing code. As a matter of fact I really
    don't have any idea how to go about this.
    I read that Swing requires repaints be done in the
    event dispatch thread. If I start the parsing in a seperate
    thread how do I update the progressbar from the other
    thread? I'm a thread neophyte.
    I need a cigarette.

    In other words do this:
    Inside event Thread:
    handle button action
    start thread
    return from action listener
    Inside worker Thread:
    lock interface
    loop
    perform action
    update progress bar
    unlock interface
    return from worker ThreadDoesn't updating the progress bar (and locking/unlocking the interface components) from within the worker thread violate the rule that you shouldn't mess with Swing components outside the event thread? (Do I have that rule right?)
    In any case, is there any way to just post some kind of event to the progress bar to update it from within the worker thread, thereby insuring that the GUI progress bar update is being invoked from the event thread? This would also obviate the need to use a timer to poll for an update, which I think is a waste especially when the monitored progress is at a variable rate, (or for number crunching, is executing on different speed machines).
    Also, doesn't using invokeLater() or invokeAndWait() still block the event dispatching thread? I don't understand how having a chunk of code started in the event thread doesn't block the event thread unless the code's executed in a "sub-thread", which would then make it not in the event thread.
    I'm also looking to have a progress bar updated to monitor a worker thread, but also want to include a "Stop" button, etc. and need the event queue not to be blocked.
    The last thing I can think of is to implement some kind of original event-listener class that listens to events that I define, then register it with the system event queue somehow, then have the worker thread post events to this listener which then calls setValue() in the progress bar to insure that the bar is updated from the event queue and when I want it to be updated. I don't know yet if it's possible to create and register these kinds of classes (I'm guessing it is).
    Thanks,
    Derek

  • Swing GUI for Javadoc

    Hi everyone,
    I'm trying to learn some basic IO and Swing. My project is to make a Swing GUI for javadoc. It's supposed to run at least under W2K and XP.
    The Swing part is going fine, but I can't seem to get IO-part working.
    I tried working with the Runtime- and the Process-class, but I don't can't seem to execute javadoc or read any command-line output. Here's a sample of code that compiles ok, but doesn't do anything.
    try {
    Process p = Runtime.getRuntime().exec("javadoc");
    InputStream in = p.getInputStream();
    String s = in.toString();
    System.out.println(s);
    System.out.println();
    System.out.println(process.waitFor());
    System.out.println();
    System.out.println(process.exitValue());
    System.out.println();
    System.out.println(""+process);
    } catch (Exception e) {
    System.out.println("error");
    if anyone has any tips, suggestions or simple code samples, I would be very happy to hear from you.

    Alright, I figured out how to read the inputstream, but
    I still get an error:
    Windows 2000
    start
    <ERROR>
    javadoc: No packages or classes specified.
    and the program doesn't terminate for some reason.
    here's the new sourcecode:
    import java.io.*;
    public class JavaDocCommander {
         public static void main(String[] args) {
              System.out.println(System.getProperty("os.name"));
              System.out.println("start");
              new Test();
              System.out.println("slut");
    class Test{
         public Test(){
              try {           
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("javadoc");
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<ERROR>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    System.out.println("</ERROR>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
              

  • Java Swing GUI Button Image

    Hi, I really need help with this one, I have tried many things and looked at many pages for this but to no avail as of yet.
    I have a Swing GUI in which I want to display an image. The way I am displaying it at the moment is as a button icon as I do not need to be able to alter the images. I can also use the button functionality as displaying something when the image is clicked. So I have an array of image paths which are accesed to load an image into the button and a "Next" button to change the image as required.
    My problem is that when I load an image into the button it moves from it's original location. When there is no image displayed the button is where I want it to be, but when I load an image it moves, this cannot happen. Any ideas.
    Also, when I am trying to click thru the array of images, it starts at the 1st image in the array but then skips to the last image in the array. Here is the code for that.
    // Handle events that arise from the "Next" button being clicked
    private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {
    if (jComboBox1.getSelectedIndex() == 1)
         for (int i = 1; i < juniorImageIndex.length; i++)
         jButton8.setIcon(new javax.swing.ImageIcon(juniorImageIndex));
    else if (jComboBox1.getSelectedIndex() == 2)
         for (int i = 1; i < seniorImageIndex.length; i++)
         jButton8.setIcon(new javax.swing.ImageIcon(seniorImageIndex[i]));
    juniorImageIndex and seniorImageIndex are obviuosly the arrrays with the file paths for the images. The reason I start at index 1 is that I use the 0 index image as the starting image for each part.
    Any help gratefully appreciated, I really hope someone can help, Thanks.

    // Handle events that arise from the "Next" button
    being clicked
    private void
    jButton5MouseClicked(java.awt.event.MouseEvent evt) {
      myImageIndex =(myImageIndex + 1) % imageArray.size();
      resetButtonImage();
    private void resetButtonImage() {
    if (jComboBox1.getSelectedIndex() == 1)
    {//take this out
    //> for (int i = 1; i < juniorImageIndex.length; i++)
    //> {
    jButton8.setIcon(new//> javax.swing.ImageIcon(array[myImageIndex]));
    //> }
    else if (jComboBox1.getSelectedIndex() == 2)
    {//this too
    //> for (int i = 1; i < seniorImageIndex.length; i++)
    //> {
    jButton8.setIcon(new
    javax.swing.ImageIcon(array2[myImageIndex]));//> }

  • Freezing Swing GUI...

    Hi!
    I am having problems with my swing GUI. It's freezing when I'm trying to disable a JButton in it. Could anybody tell me y it happens and what can be done to remedy it?
    My piece of code:
    stopButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // stop!
    simulator.blinker = null;
    label.setText("Stopped!");
    playPauseButton.setEnabled(false);
    stepButton.setEnabled(false);
    showNamesButton.setEnabled(false);
    speedUpButton.setEnabled(false);
    speedDownButton.setEnabled(false);
    stopButton.setEnabled(false);
    When I press the stopButton, my GUI freezes. Same happens with this piece of code when simSpeed = 50:
    speedUpButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (simulator.simSpeed > 300 && simulator.simSpeed <= 500){
    simulator.simSpeed -= 100;
    System.out.println("sim speed = " + simulator.simSpeed);
    else if (simulator.simSpeed > 50 && simulator.simSpeed <= 300){
    simulator.simSpeed -= 50;
    System.out.println("sim speed = " + simulator.simSpeed);
    else {//if (simulator.simSpeed == 50){
    System.out.println("caution: sim speed = " + simulator.simSpeed);
    speedUpButton.setEnabled(false);
    Strangely, this one does not make the GUI freeze when simSpeed = 1500:
    speedDownButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (simulator.simSpeed < 1500){
    simulator.simSpeed += 100;
    System.out.println("sim speed = " + simulator.simSpeed);
    else if (simulator.simSpeed == 1500)
    speedDownButton.setEnabled(false);
    I'd greatly apreciate any help!
    Thx in advance!
    Owrwe

    I have gone thru some experimentations and come to this conclusion:
    when i try to disable buttons at the extremity of a row of buttons, the GUI freezes!
    for example:
    buttonPanel.add(speedUpButton);
    buttonPanel.add(speedDownButton);
    buttonPanel.add(playPauseButton);
    buttonPanel.add(stepButton);
    buttonPanel.add(showNamesButton);
    buttonPanel.add(stopButton);
    this is the order of buttons in a layout (flow layout by default, isn't it?). The GUI freezes when I try to disable: speedUpButton and stopButton (from inside their ActionListener method).
    Changing the layout to:
    buttonPanel.add(speedDownButton);
    buttonPanel.add(speedUpButton);
    buttonPanel.add(playPauseButton);
    buttonPanel.add(stepButton);
    buttonPanel.add(showNamesButton);
    buttonPanel.add(stopButton);
    The GUI freezes when I try to disable: speedDownButton (as compared to speedUpButton from above) and stopButton (from inside their ActionListener method).
    Changing the layout to:
    buttonPanel.add(playPauseButton);
    buttonPanel.add(speedDownButton);
    buttonPanel.add(speedUpButton);
    buttonPanel.add(stepButton);
    buttonPanel.add(stopButton);
    buttonPanel.add(showNamesButton);
    The GUI freezes when I try to disable: all of them (from inside the stopButton ActionListener). The speedUpButton and speedDownButton are properly disabled when the limits are reached without freezing the GUI. If I disable all buttons (thru the stopButton when it's not at the extremity of the row) except one of them, the GUI doesn't freeze!
    any suggestions?

  • 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

Maybe you are looking for