throw an exception in code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • blazedaces
    Contributor
    • May 2007
    • 284

    #46
    First of all, as they have all said previously, please, Dlangdaman, read the tutorials. If you did I'm sure all your questions would have been answered already. I do not believe you read/tried the tutorial because most of the topics are explained there.

    Do you not understand that you're honestly wasting more time this way? Just do the tutorial, I did that tutorial as well way back when, I know it's not as big a deal as you're making it out to be...

    Now, perhaps this is just something you're not understanding about all things in programming: different topics are ... different. Though that was a snide remark I'm just trying to get my point across.

    You asked how to bring up a gui-like question dialog box asking about whether to continue if bla bla. These are all separate topics, figure out first how to throw an exception, then move onto these issues, one step at a time man.

    Listen, throwing an exception does just that, throws an exception. It's like putting up a warning sign on the road whenever there's construction. Except java works so that when it sees a warning sign (exception) it has to respond (people sometimes ignore warning signs and that's why we have accidents... among other reasons).

    The response is what you want to be done when the exception occurs. See what Jos wrote in the above post? If you tried the exception tutorial and did some proper research you would understand what the try and catch wrappers do, but I'll basically explain it to you:

    Everything wrapped inside try is basically waiting to catch an exception and everything inside catch is what you do when you catch that exception.

    So referring again to what jos wrote above, you would somewhere, maybe your main write

    [code=java]
    try {
    // your code here that can throw exception X
    }
    catch(X x) {
    // your code did throw exception X; handle it here
    }
    [/code]

    Where you "handle" it you would do what you want, like popping up a menu and asking the user if they want to stop or continue?

    Again, just as jos said, please understand, we want you to understand *how* this works, not just *make* it work.

    Good luck,

    -blazed

    Comment

    • tnga
      New Member
      • Jul 2007
      • 27

      #47
      I bet he is making fun of everyone here.
      The tutorial is very explanatory, and he would learn the try/catch coding very easily!
      I don't want to be seen as hostile either, I'm just giving my point of view.

      Focusing on the topic:
      You have to put the piece of code that may cause the exception inside the try statement and with a conditional clause throw the exception when appropriated.
      Then, inside the Catch statement, you should put what to do when that exception is thrown, for example show a message telling that the grades are out of bounds...

      Sorry my awful english.
      Best regards

      TNGA

      Comment

      • Dlangdaman
        New Member
        • Jun 2007
        • 36

        #48
        well I must say that you guys love to make someone who is trying to learn feel STUPID..just because you have a lot more experience or TIME to understand the concepts here...doesnt mean everyone does...
        here is the code I have that throws an exception which in turn kills the app...

        Code:
        import javax.swing.JOptionPane;
         
        public class Grades
        {
               
           public Grades()
            {
                float grades [] = new float[5];
                float ave, sum = 0.0f;
                String students[] = {"Tim", "Mary", "Jen","Derek", "John"};
                String sgrades, sResult;
                
                int i;
                for(i = 0; i < grades.length; ++i)
                {
                    sgrades = JOptionPane.showInputDialog(null,
                            "Enter the Student's Grade: ", students[i],1);
                            grades[i] = Float.parseFloat(sgrades);
                            if(grades[i] > 100 || grades[i] < 0)
                            throw new InvalidGradeException("Invalid grade.");
                            
                }
                for(i = 0;i < grades.length; ++i)
                    
                {
                    sum += grades[i];
                }
                ave = sum / 5.0f;
                sResult = "The Class average is " + Float.toString(ave);
                JOptionPane.showMessageDialog(null,sResult);
           }
            public static void main(String args[])
            {
                new Grades();
                System.exit(0);
            }
           class InvalidGradeException extends NumberFormatException {
            public InvalidGradeException(String s) {
                super(s);
            }
         
        }
        }
        please help in any way you can...and please understand i am a NOVICE>...learn ing...to put me down and make snide remarks...is uncalled for....and honestly..that tutorial does not do that well

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #49
          Originally posted by Dlangdaman
          well I must say that you guys love to make someone who is trying to learn feel STUPID..just because you have a lot more experience or TIME to understand the concepts here...doesnt mean everyone does...
          here is the code I have that throws an exception which in turn kills the app...
          You're asking for what you've been doing wrong and we point it out, no more,
          no less and nothing personal. Again, you are not catching the exception that
          was thrown so the exception ends up somewhere in the java virtual machine
          itself. Of course it doesn't know what to do with it so it simply prints out the
          complete stack trace and terminates.

          Read my previous reply where I outlined how to catch an exception: basically
          if any (block of) code or method or whatever can throw an exception you should
          put that piece of code in a try { <your code here> } catch( ... ) { ... } block.

          kind regards,

          Jos

          Comment

          • r035198x
            MVP
            • Sep 2006
            • 13225

            #50
            I bet I don't have as much time on my hands as you have.
            Mathematics

            Division by zero is illegal.
            If I write a piece of code that divides a number by zero, what will the JVM do? (I say the JVM because I can put both values in variables so that the compiler won't be able to tell what could be in those variables). Here's some code (since you want code so much)

            [CODE=java]double ireally = 5.0;
            double liketo = scanner.nextDou ble();
            double help = ireally / liketo;[/CODE]
            Now line 3 there is illegal.
            The JVM throws an exception if you divide by zero. the name of the exception thrown is java.lang.Arith meticException
            Now I can catch this exception using a try / catch block like this
            [CODE=java]double ireally = 5.0;
            double liketo = scanner.nextDou ble();
            try {
            double help = ireally / liketo;
            }
            catch(Arithmeti cException e) {
            System.out.prin tln("I'm caught here!");
            }
            System.out.prin tln("Program was not destroyed and continues here");[/CODE]

            I put the code that may throw the exception in the try block and handle the exception in the catch block.

            Comment

            • tnga
              New Member
              • Jul 2007
              • 27

              #51
              It is killing the app because you are throwing an exception and never catching it. When you throw an exception java searchs for a catch statement that catches that exception...
              You should place your "if (grade >100 || grade < 0)" comparison inside a try { } statement and then inside a catch { } statement treat the exception as you wish... for example printing "Invalid grade" on the screen.

              I hope that helps.

              Best regards,

              TNGA

              Comment

              • dmstn
                New Member
                • Feb 2007
                • 16

                #52
                Alternatively you could do something like that. You could create a method that gets your input. I mean when you enter the grade that method is going to receive it and will look like that:

                Code:
                 
                
                import java.util.Scanner;
                
                public class Grades {
                
                     int x;
                     Scanner x = new Scanner(System.in);
                    public getGrades(int grade) [B]throws GradesException[/B]
                    { 
                      System.out.println("Enter grade, please: ");
                      grade = x.nextInt();
                      //your code here
                     //your code here.....
                
                    if(grade < 0 | grade > 100) [B]throw new GradesException(); [/B]}
                You have yet to create the exception class. It should look like that:

                Code:
                 
                import java.io.*;
                
                public class GradesException extends Exception {
                
                                public GradesException() {}
                                public GradesException(String msg) {
                                    super(msg);
                                }
                            }
                I hope this has helped.

                Comment

                • r035198x
                  MVP
                  • Sep 2006
                  • 13225

                  #53
                  Originally posted by dmstn
                  Alternatively you could do something like that. You could create a method that gets your input. I mean when you enter the grade that method is going to receive it and will look like that:

                  Code:
                   
                  
                  import java.util.Scanner;
                  
                  public class Grades {
                  
                       int x;
                       Scanner x = new Scanner(System.in);
                      public getGrades(int grade) [b]throws GradesException[/b]
                      { 
                        System.out.println("Enter grade, please: ");
                        grade = x.nextInt();
                        //your code here
                       //your code here.....
                  
                      if(grade < 0 | grade > 100) [b]throw new GradesException(); [/b]}
                  You have yet to create the exception class. It should look like that:

                  Code:
                   
                  import java.io.*;
                  
                  public class GradesException extends Exception {
                  
                                  public GradesException() {}
                                  public GradesException(String msg) {
                                      super(msg);
                                  }
                              }
                  I hope this has helped.
                  Then they'd still still need the try/catch block to handle the exception when it gets thrown of course.

                  Comment

                  • flutterby75
                    New Member
                    • Jul 2007
                    • 5

                    #54
                    Originally posted by Dlangdaman
                    can you lead me through setting up an exception that give a GUI ok or cancel and then lets them proceed with entering? i have it throwing an exception now but it just kills the program
                    I'm reading this and wondering why don't you just forget the exception and use an alert dialog box? It would come up (when placed as a result of an if...statement being false) and the user could click ok/cancel and proceed. It's one helluva lot less work and far simpler to program as a novice when all you want is what you've stated above.

                    regards...flutt

                    Comment

                    • JosAH
                      Recognized Expert MVP
                      • Mar 2007
                      • 11453

                      #55
                      Originally posted by flutterby75
                      I'm reading this and wondering why don't you just forget the exception and use an alert dialog box? It would come up (when placed as a result of an if...statement being false) and the user could click ok/cancel and proceed. It's one helluva lot less work and far simpler to program as a novice when all you want is what you've stated above.

                      regards...flutt
                      I doubt it; I think that the code will end up simpler when exceptions are used
                      instead of a more complicated control flow; I could be wrong of course for this
                      particular example. What I always do is implement both and see which one
                      comes out as the winner.

                      kind regards,

                      Jos

                      Comment

                      • flutterby75
                        New Member
                        • Jul 2007
                        • 5

                        #56
                        Originally posted by JosAH
                        I doubt it; I think that the code will end up simpler when exceptions are used
                        instead of a more complicated control flow; I could be wrong of course for this
                        particular example. What I always do is implement both and see which one
                        comes out as the winner.

                        kind regards,

                        Jos
                        To create and throw your own exception you have to write a whole new exception class, a try -catch clause, a finally statement etc...an alert dialog box is nowhere near as complicated, nowhere near as much code to write for starters. It suits what you're looking for far better IMO.

                        kind regards, Flutt...

                        Comment

                        • flutterby75
                          New Member
                          • Jul 2007
                          • 5

                          #57
                          Originally posted by JosAH
                          I doubt it; I think that the code will end up simpler when exceptions are used
                          instead of a more complicated control flow; I could be wrong of course for this
                          particular example. What I always do is implement both and see which one
                          comes out as the winner.

                          kind regards,

                          Jos
                          doh! apologies I thought I was writing back to OPand addressed it to him/her!It's been along day!

                          I was just thinking, 1.he/she's a novice and coding for an alert box is far far simpler...2. it's far less code to write..and 3.all he/she wants is something to appear on the GUI for the user to ok or cancel...plus the other stuff I mentioned in above post...all this to me says alert box not exception.

                          kind regards, Flutt..

                          Comment

                          • tnga
                            New Member
                            • Jul 2007
                            • 27

                            #58
                            Originally posted by flutterby75
                            doh! apologies I thought I was writing back to OPand addressed it to him/her!It's been along day!

                            I was just thinking, 1.he/she's a novice and coding for an alert box is far far simpler...2. it's far less code to write..and 3.all he/she wants is something to appear on the GUI for the user to ok or cancel...plus the other stuff I mentioned in above post...all this to me says alert box not exception.

                            kind regards, Flutt..
                            Well, maybe he/she is doing homework and there is a specific requirement on using exceptions. Even when the result doesn't require that, teachers may ask to use exceptions, so that students would practice.
                            Even though not using exceptions would resolve his/her problem, it would be very nice for him/her to learn it anyway...

                            Best regards,

                            Thiago

                            Comment

                            • flutterby75
                              New Member
                              • Jul 2007
                              • 5

                              #59
                              Originally posted by tnga
                              Well, maybe he/she is doing homework and there is a specific requirement on using exceptions. Even when the result doesn't require that, teachers may ask to use exceptions, so that students would practice.
                              Even though not using exceptions would resolve his/her problem, it would be very nice for him/her to learn it anyway...

                              Best regards,

                              Thiago
                              This is true :-) I just took it on face value. It seems rather a simple situation to use an exception for though..?

                              I personally found exceptions very difficult to learn about..actually a right pain in the *rse! I would suggest any advice from anyone is beneficial in this area.

                              Kind regards, Flutt...

                              Comment

                              • r035198x
                                MVP
                                • Sep 2006
                                • 13225

                                #60
                                I hope the OP realized here that there is also the possibility of an InputMismatch Exception from scanner.nextInt and should ideally catch this as well.

                                Comment

                                Working...