Exceptions vs defensive programming

Hi...
Which of the following two code fragments is 'better'... bearing in mind that Java's exception handling syntax is commonly touted as aiding readability, allowing programmers to focus on the 'task' rather than a nest of 'if' statements and suchlike? I'm just askin' outta interest's sake...
Fragment 1...
public void actionPerformed (final ActionEvent e) {
     if (_target != null && _clipboard != null) {
          Transferable clipContents = _clipboard.getContents (null);
          if (clipContents != null) {
               if (clipContents.isDataFlavorSupported (DataFlavor.stringFlavor)) {
                    try {
                         String contents = (String) clipContents.getTransferData (DataFlavor.stringFlavor);
                         if (_target.getSelectedText () != null) {
                              //replace the selection with the contents of the clipboard
                              _target.replaceSelection (contents);
                         else {
                              //insert the contents of the clipboard ahead of the current insertion point
                              int insertionPoint = _target.getCaretPosition ();
                              _target.getDocument ().insertString (insertionPoint, contents, null);
                    catch (final BadLocationException ble) {
                         //bleep! **((*!@4%@!! :D
                         Toolkit.getDefaultToolkit ().beep ();
                    catch (Exception ignoredForNow) {}
}Fragment 2...
public void actionPerformed (final ActionEvent e) {
     try {
          Transferable clipContents = _clipboard.getContents (null);
          if (clipContents.isDataFlavorSupported (DataFlavor.stringFlavor)) {
               String contents = (String) clipContents.getTransferData (DataFlavor.stringFlavor);
               if (_target.getSelectedText () != null) {
                    //replace the selection with the contents of the clipboard
                    _target.replaceSelection (contents);
               else {
                    //insert the contents of the clipboard ahead of the current insertion point
                    int insertionPoint = _target.getCaretPosition ();
                    _target.getDocument ().insertString (insertionPoint, contents, null);
     catch (final BadLocationException ble) {
          //bleep! **((*!@4%@!! :D
          Toolkit.getDefaultToolkit ().beep ();
     catch (final NullPointerException npe) {
     catch (Exception ignoredForNow) {}     
}

I totally disagree with not having more than one return statement.
I have had to maintain code like this and it is a total mess:
    boolean continue = true;
    int a = getSomeInfo();
    continue = someCheck(a);
    if (continue) {
        // do some stuff with a
        continue = someCondition();
    if (continue) {
       // do some other stuff with a
       continue = anotherCondition();
    //etc.
    return a;
}The problem with this is really hard to detemine what gets returned when you try to read the code. I think the idea that one exit point in a function makes things more simple is total crap. Sometimes it is better but I'd rather see this.
    boolean continue = true;
    int a = getSomeInfo();
    if (someCheck(a)) return a;
    // do some stuff with a
    if  (someCondition()) return a
    // do some other stuff with a
    if (anotherCondition()) return a;
    //etc.
    return a;
}This way you at least have the compiler on your side helping you make sure your conditions are reachable and so forth. Also, in any decent editor keywords like return are easy to spot and therefore are easier to see than a = something(). The idea of a single exit point was very valid before try catch finally, it helped make sure clean up was done. With finally you can forget that rule.
Here's another good example where one exit point can be a pitfall.
public String method(int value){
   String returnString;
   switch (value) {
      case 1:
         returnString = "one";
         break;
      case 2:
         returnString = "two";
      case 3:
         returnString = "three";
    return returnString;
}There are two major problems with this code that may not be immediately obvious (more so in a more realistic and complicated example.) 1. If the value entered is not 1, 2 or 3 the method returns null (which you may or may not want.) 2. if the user enters 2 the result will be "three"
Now if you use multiple returns both of these problem are non-existant
public String method(int value){
   String returnString;
   switch (value) {
      case 1:
         return "one";
      case 2:
         String returnString = "two";
      case 3:
         return "three";
}Problem 1 will now cause a compiler error because not all paths of the method return a value.
Problem 2 will cause the same error because you are not returning anything for 2 and there is no return statement after the switch.

Similar Messages

  • Defensive programming vs exception handling

    Hi
    im new to java programming and having problems getting my head around defensive programming vs exception handling.
    i've read in my uni books about design by contract and the idea of defensive programming but im having problems with it.
    so say i write the code.
    String container = //some value
    if (container.equals.("")) // so if i am looking for a value and find a empty String
       throw new // a custom exception i have made for this error.
    else
       //do whatever i had planned with a non-empty String
    }is this Defensive programming or exception handling. Or am i complete of base.
    thanks

    jverd wrote:
    JustSomeGuy wrote:
    Don't fall into the trap of saying "Meh, the exception will handle it". If you can forsee something easily being a problem, and it can be controlled, then control it. Save the exception handling for those things you don't forsee and those you can't control. I disagree. Or at least, I disagree with what I think you're saying.
    For instance, if null is not a valid argument, then document it, and don't waste code defending against it. Either throw an explicit IllegalArgumentException, or let the NPE be thrown.
    And absolutely under no circumstances should you ever write code that will deliberately lead to an exception, Eh? If an exceptional condition occurs, you should delibrately throw an exception. Consider if you will the following code snippet
    import java.io.*;
    class ExceptionExample {
        public static void main(String[] args)
            throws IOException {
            if (args.length == 0) {
                System.out.println("Must give filename as first arg.");
                return;
            FileInputStream in;
            try {
                in = new FileInputStream(args[0]);
            catch (FileNotFoundException e) {
                System.out.println("Can't find file: " + args[0]);
                return;
            int ch;
            while ((ch = in.read()) != -1) {
                System.out.print((char) ch);
            System.out.println();
            in.close();
    } What I was saying in the first part is shown with the following part of the above code
    if (args.length == 0) {
       System.out.println("Must give filename as first arg.");
       return;
    } Would the exception handler that follows this peice of code have taken care of that? Sure! Would it be the best choice to just let the exception handler do it? No way no how!
    It is easy to forsee someone forgetting or not realizing they need to add the filename as an arg and it can be controlled, so in this and most cases just like it the best choice is to either inform the user with a more specific statement than could be used in the exceptionhandler and do nothing or fix it yourself like for instance by using a default filename.
    What I meant by deliberately throwing an exception can be illustrated with this small portion of my code above
    int ch;
    while ((ch = in.read()) != -1) {
        System.out.print((char) ch);
    } A -1 to mark the EOF is expected and reaching the EOF is expected. There is absolutely nothing abnormal about this, so it should not be handled by an exception. But far to often I have seen novice and especially "think they know it all novices" use an exception in place of exactly this. They know the file will end, they know they must do something about that, but instead of doing it right they just set it up so an exception will be thrown and they can just handle it in the exceptionhandler. This is what I meant by deliberately throwing exceptions, in that an exception must be thrown in order for their program to work as intended. Bad, very bad.
    Now that I have provided an example and further clarified my position do you still disagree? I can't imagine you would, so if you do I would be very interested in getting some further insight into your reasoning.
    JSG

  • Is defensive programming out?

    Hi,
    I wondered if I am a naturally talented software tester, because on trying some random software I easily find ways to make it segfault.
    Two examples from today include rosegarden and kazehakase.
    rosegarden, default configuration:
    Start it, doubleclick on the first measure, choose menu "segment" -> "new layer", click the undo button, enjoy segfault.
    kazehakase, default configuration:
    Start it, choose menu "view" -> "ui level" -> "medium" or "expert", choose menu "view" -> "view page source" while no tab is open (as it is with default config on first start), enjoy segfault.
    So first kazehakase: Yes, I know it is a very early version. But I can live with missing functionality like "view page source" doing nothing. The problem is crashing on issueing such command. Without looking at the code I bet this is a null pointer (because there is no page displayed) of which the developer thought "oh, this probably won't ever be null".
    Next is rosegarden which wants to be "professional".
    I believe this bug with "undo" to be similar to the one in kolourpaint (start kolourpaint, choose text tool and write a letter, press strg+a, strg+z, this should be fixed, but at least now not in the repos.). Maybe it's a problem in qt in general or a problem with implementing "undo" in general. I don't care.
    When implementing an undo function I would be EXTREMELY careful to what happens in this functions.
    You have to be ready to undo ANYTHING that the user can possibly do in your program which is hell of a lot.
    In these programs people apparently didn't use defensive programming: I can see the programmer sitting there and think about how to undo several things but not how to handle something coming into his undo function that it cannot undo.
    I also believe plasma from KDE to crash so much instead of displaying an error message because of that.
    The question I ask myself is: Why do I see so many segfaults and so few error messages?
    Is it time for a kernel API to inform the application that it segfaulted and give it a chance to recover, maybe even with user intervention?
    Last edited by Cdh (2010-06-27 20:43:51)

    bernarcher wrote:
    I think defensive programming, even "simple" exception handling, never was widely used. It is by no means trivial and tends to bloat the code, esp. in languages with no exception handling mechanisms built in, like C for instance.
    Even using languages which do provide fairly good mechanisms for exception handling (like e.g. Eiffel, or D) it is difficult to catch edge cases in a meaningful way (other than simply finishing program execution). More often than not exceptions do not occur locally to the program part which really needs to handle the situation. And if they do they lead to more or less combinatorial explosion if not thoroughly planned. Thus, making a programm foolproof from start as "defensive programming" mandates is a tremendous effort (and not overly exciting to do).
    Even if you try to handle system signals, things tend to be involved and complicated. Just have a look at theSignal Concepts in the Open Group  Base Specification. Or have a look at man signal and related man pages.
    This is not to state defensive programming to be fruitless. But the efforts in time (and money) are most often not taken. You can't easily show built-in defenses. Being able to get a program "just running" and showing some effects appears far more exciting.
    It is like thorough testing (beyond running a unit test suite), and documenting (both software and user sides) - most desirable, but not many want to really do the works.
    Well said. I can't really elaborate on this but I'd have to wholeheartedly agree.
    (Sorry I can't elaborate I whenever i'm coding something thats one of the few things I try to look out for).
    Last edited by Ari'osika (2010-06-28 09:49:05)

  • I've downloaded CS6 Master Collection but only see The Photoshop icon.  I can't seem to find the other programs, except on "uninstall programs" How do I open and run the others?

    I've downloaded CS6 Master Collection but only see The Photoshop icon.  I can't seem to find the other programs, except on "uninstall programs" How do I open and run the others?

    How about you give us some real information.
    Did you install the software? What operating system?

  • Contract and defensive programming

    I'm exploring the differences between Contract and Defensive programming. I'm seeking any comments from the community on the subject of these two apparently opposing paradigms. (Or am I wrong? Do they oppose?)
    Contract Programming, or Design by contract, is a programming paradigm whereby classes define their behavior and interplay by "contracts" which are defined in terms of pre-conditions, post conditions and class invariants. In this paradigm, the code must "fail hard", and resist verifying that the contract conditions are met.
    Defensive programming is an opposite strategy. In this paradigm, the assumption is made that the pre conditions of a method call ought to be tested within the method for assurance. This can lead to extra development and a potential veiling of errors elsewhere, such was where and how the call is made.
    My question is, which of these is the preferred method, or ideology of development and why?
    Thanks for any feedback and links to external sources which may be helpful.

    Just asking a clarifying question:
    I'm not sure of the difference between the 2, and my understanding is Java doesn't 'directly' support Design by Contract. I have only
    seen this in Eiffel (in school), but my question, aren't manually coded 'precondition checks' the way to support Design by Contract in Java?
    lance.walton wrote>
    <The important difference, which you've kind of alluded to, is that defensive programming tries to consider what contract violations might occur and provide <strategies for dealing with this. The result is more code that will ideally never be executed. This clutters the intent of what you're trying to achieve as well <as probably introduce more defects because of the clutter. It also suggests that the client code might make mistakes that you can help it with.
    <
    <Even if you don't do Design by Contract (hard to do properly in Java), I would not do defensive programming. It allows sloppy client code, and that <allowance then has to be maintained, which will get harder and harder as your code evolves until you start talking about a rewrite because it's such a <mess.
    If you want to protect yourself against poor client code, use precondition checks.

  • Exception handling in program

    Hi All,
         I have a class in one of the methos I'm raising an exception. When I'm calling that method in my program and when the exception is raised it is throwing a runtime error. The exception is no a system based exception it is an exception which is raised by me in the method only.
        Can anyone tell how to handle that exception in the program. My class name is zaccounts,
    the exception I'm raising is insufficient_fund.
    Many thanks!!!!

    Hi,
    Make sure you uncomment the exceptions part.
    if you still want to handle it further you can do that by using the RAISED exception
    Best Regards
    Ramchander Rao.K

  • Uninstall PC Theft Defense Program????

    Hi, I just bought this new Sony Laptop from Best Buy and installed the program PC Theft Defense program that gives you 3 years of free service in case your Laptop is stolen.   Well after installing it I realized that it wasn't  something that I needed as i am disabled with a back injury and the laptop never leaves my house/side so there would be no way it could be stolen.  
    The reason I am writing is because the icon keeps coming up where the clock is on the right and when I tried uninstalling it from the Control Panel there is "no option to uninstall" it like all the other programs that are in my Laptop.    I deleted the programs off my C:/ drive but it keeps coming up and showing in the icon area, I know I can shut it off so it doesn't show in there but it will still  be starting, at least this way I can exit it when I start my Laptop so it doesn't use up resources that don't need to be.
    So is there a way to remove this software somehow??   I'd hate to have to bring it in to Best Buy for them to remove if there is an easy out for me.   I went to the PC Theft site and signed in and it said there are no computers set up for this service so I think I cancelled it somehow the right way just want it off my Laptop.  Thanks, Jim

    harleynh wrote:
    Hi, I just bought this new Sony Laptop from Best Buy and installed the program PC Theft Defense program that gives you 3 years of free service in case your Laptop is stolen.   Well after installing it I realized that it wasn't  something that I needed as i am disabled with a back injury and the laptop never leaves my house/side so there would be no way it could be stolen.  
    The reason I am writing is because the icon keeps coming up where the clock is on the right and when I tried uninstalling it from the Control Panel there is "no option to uninstall" it like all the other programs that are in my Laptop.    I deleted the programs off my C:/ drive but it keeps coming up and showing in the icon area, I know I can shut it off so it doesn't show in there but it will still  be starting, at least this way I can exit it when I start my Laptop so it doesn't use up resources that don't need to be.
    So is there a way to remove this software somehow??   I'd hate to have to bring it in to Best Buy for them to remove if there is an easy out for me.   I went to the PC Theft site and signed in and it said there are no computers set up for this service so I think I cancelled it somehow the right way just want it off my Laptop.  Thanks, Jim
    I wonder if its controlled on a BIOS level... If disabled in  the BIOS the software won't react no more?
    *******DISCLAIMER********
    I am not an employee of BBY in any shape or form. All information presented in my replies or postings is my own opinion. It is up to you , the end user to determine the ultimate validity of any information presented on these forums.

  • How to flag shell script if there is a exception in java program

    Hi all,
    can someone let me know if it possible to flag the calling shell script that there is a exception in java program ???
    Thanks
    Chat

    have a question
    In the shell script if I read for ret_stat=$? , will it give the value of 33 if exception occurs ?

  • How to get text of exception in my program, exception is defined in FM?

    I have written a function module where i have defined a couple of exceptions. If an error occurrs i raise the exception.
    My issue is, in my calling program, i call the function module i have created and once the exception occurrs i need to get the text associated with that exception.
    I dont know how to get the text of the exception. The short text is defined in exception tab of the function module.
    Any help will be appreciated.
    Thanks

    hi check this example..
      RECEIVE RESULTS FROM FUNCTION 'ZMARD_DATA'
         IMPORTING
           E_RECORDS  = g_records
         EXCEPTIONS
           no_data                            = 1
           open_dataset_no_authority          = 2
           convt_codepage_init                = 3
           dataset_too_many_files             = 4
           unknown_file_opening_error         = 5
           dataset_write_error                = 6
           dataset_not_open                   = 7
           dataset_cant_close                 = 8
           OTHERS                             = 9.
      CASE sy-subrc.
        WHEN 0.
          error_rec-msg_text     = 'Data Loaded'.
          g_total_rec = g_total_rec + g_records.
        WHEN 1.
          error_rec-msg_text     = c_no_data.
        WHEN 2.
          error_rec-msg_text     = 'OPEN_DATASET_NO_AUTHORITY'.
        WHEN 3.
          error_rec-msg_text     = 'CONVT_CODEPAGE_INIT'.
        WHEN 4.
          error_rec-msg_text     = 'DATASET_TOO_MANY_FILES'.
        WHEN 5.
          error_rec-msg_text     = 'UNKNOWN_FILE_OPENING_ERROR'.
        WHEN 6.
          error_rec-msg_text     = 'DATASET_WRITE_ERROR'.
        WHEN 7.
          error_rec-msg_text     = 'DATASET_NOT_OPEN'.
        WHEN 8.
          error_rec-msg_text     = 'DATASET_CANT_CLOSE'.
        WHEN 9.
          error_rec-msg_text     =
                  'Unknown error calling FM : ZMIO_GET_MARD_DATA'.
      ENDCASE.

  • Exception "Cannot run program" while using ProcessBuilder class

    Hi Java-Folks,
    I try to start a program within a Java application using the ProcessBuilder class. This is the first time I use ProcessBuilder so I do not have any deep knowledge of it. Here is a snippet of my code:
    static void connectToHost(String Host) {
    ProcessBuilder pb = new ProcessBuilder("connect.exe"), Host);
    Map<String, String> env = pb.environment();
    env.put("SHELLWIDTH", "64");
    pb.directory(new File("C:\\MyProgram\\ExApp\\shell"));
    try (
    Process p = pb.start();
    } catch (IOException ex) {
    Logger.getLogger(ShellUtil.class.getName()).log(Level.SEVERE, null, ex);
    }Using this method I get an IOException which says *"Cannot run program "connect.exe" (in directory "C:\MyProgram\ExApp\shell"): CreateProcess error=2, The system couldn't find the specified file"*
    Does anybody have an idea why this is not working? I tried to start another application like "notepad.exe" and that works fine. So it seems related to the fact
    that the program I want to start is only available in a certain directory and not via the PATH env-variable.
    I would appreciate any help or hint :-)
    Regards,
    Lemmy

    Okay I guess I misinterpreted the JavaDocs regarding the directory method. The exception message is a little bit confusing too, because it seems like Java tries to find the Application within the specified
    working directory.
    I tried to use the full path with the ProcessBuilder constructor and it looks like this variant is working. I still have some trouble with the application itself but I was able to start another program which is
    not in the PATH var, using the full path to the executable.
    Thanks for the help so far.
    Bye
    Lemmy

  • How to handle exception in driver program

    Dear Friends;
         I have been assigned to  object wherein i have to display a form for which i am gathering all my data in smartform and my requirement is that when first time data selection failed i.e. no data found against selected order number (AUFNR) then i have to display information message and the return back to my selection screen wherein i am taking process order (AUFNR) from user . I guess we cannot display messages when we are in smartform function module so what i did is in my form interface i have created my own exception and i need to handle it in my driver program where it can be possible for me to display information message and return back to selection screen. But i don't know how to code it only i have is rough idea Can u please help me out???
    If possible send me example code
    Regards;
    Parag

    HI,
    Before calling the Generated Functionmodule of the smartform, just write the code to check the data and write all the validations, if any one failes, then raise the error message, then the Selection screen will come again if the error message occurs
    Regards
    Sudheer

  • Lock the entire computer, except for one program?

    I am having my 20th high school reunion this weekend and was wondering if there is a way to lock my entire MacBook except for a guestbook I would probably make in Filemaker Pro or something. Thanks in advance!

    create a normal user (no admin) , and censured all the program except filemaker. you can find this option in account setting.
    look at create user account:
    http://www.apple.com/support/mac101/work/1/

  • Programming catching exceptions to control program flow.

    Hello,
    I have the following snippet:
         public List subList(int fromIndex, int toIndex) {
              PGSearchEngineList subList = new PGSearchEngineList();
              for (int index = fromIndex; index < toIndex; index++) {
                   try {
                        subList.add(this.get(index));
                   } catch (IndexOutOfBoundsException e) {
                        return subList;
              return subList;
         }Notice that I use a try catch to catch a IndexOutOfBoundsException and to control program flow. Is this a bad practice?
    Julien Martin.

    I believe I read once that you shouldn't code an exception to deal with a condition that you could reasonably expect to occur. There is some sample code for the value list handler on the j2ee patterns page that deals with search result paging in a little "cleaner" way:
    http://java.sun.com/blueprints/corej2eepatterns/Patterns/ValueListHandler.html
    Hope this helps.
    Amber

  • Possible to catch parameters exceptions in the program ?

    Hi,
    Oracle 10g r2.
    I have some procedures/functions like :
    function insert_op (op_name in varchar2, op_date in date, op_length in number) is
    begin
    end;If I call for example :
    insert_op('test','02/05/2010','hehe')I will get an error (invalid number). Normal.
    My qyestion is, is it possible to catch that exception in the function ?
    The fact is that my function is called from an input button in my apex application, so if user enter wrong values in the form, I can't catch the error except using Javascript.
    Or should I pass all my parameters as varchar2, and then make functions to ckeck if it is valid numbers, dates, etc... :/
    Thanks.
    Yann.

    function insert_op(op_length in number) return varchar2 is
    temp number;
    begin
    temp := TO_NUMBER(op_length);
    return 'ok it is a number';
    exception
    when others then return 'not a number';
    end;Define the op_length as varchar2
    create or replace function insert_op(op_length in varchar2) return varchar2 is
    temp number;
    begin
       temp := TO_NUMBER(op_length);
       return 'ok it is a number';
    exception
    when others then return 'not a number';
    end;And further most important thing is dont use WHEN OTHERS. Use the specific exception. In this case VALUE_ERROR.
    I have done such thing in the past. Here is that code.
    create or replace function is_number(pVal in varchar2) return number
    as
       lNum number;
    begin
       lNum := to_number(pVal);
       return 1;
    exception
       when value_error then
               return 0;
    end;Edited by: Karthick_Arp on Mar 1, 2011 5:26 AM

  • Defensive programming - error labels

    How do I use labels to point out where an error has occured? Right now I have a simple JFrame interface with radio buttons and text fields. What I want are labels that appear next to these items if an error occurs at any. For example, a radio button might not have been selected when the 'proceed' button is pressed, so a label will point this out.
    I have put in the labels, I just need to know how to link these to the code. In other words, I need them to be not visible by default and set to visible when en error occurs. Also, will throwing an exception terminate the method call? (I should know this)

    We did something similar to denote required fields.
    Every field would have an associated JLabel. Each label consists of an icon + text. For required fields, the icon was a 5 pixel red asterisk. For the non-required fields, we used a blank, transparent gif that was also 5 pixels wide. If the field was required, the required icon was "turned on" (the red asterisk icon was set on the label), and if the field was not required or already filled in, the required icon was "turned off" (the blank icon set on the label).
    The icons were of the same width to prevent "shifting" as the indicator would go on/off, and so that the text of the labels would be left-aligned with neighboring labels above or below regardless of the indicator being on/off.

Maybe you are looking for