Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Catch without a try error

  1. #1
    Member
    Join Date
    Oct 2013
    Posts
    31
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Catch without a try error

    I'm doing a project where I have to catch a user inputting a string into one of the prompt.
    Problem is it seems I always get catch without a try error no matter what I do.
    it keeps saying expected ";" on the catch statement... which is incorrect.
    error(s) are appearing at line 49 - try without a catch.
    Line 102 - catch without a try.
    line 92 - while statement is unreachable.
    and line 107 which is a bracket it says " class, or enum expected".
    I couldn't tell you what I did fix because my original code was something completely different so I restarted a few things to fix certain problems that could occur.
    I've looked around the internet found bad examples to try to fix my code with myself.

    //This is a program that will calculate a monthly payment and loop it. If user gives bad data you will be prompted.
     
    package monthypayment2;
    import java.text.NumberFormat;
    import java.util.Scanner;
     
     
    public class Monthypayment2 {
        private static double monthlypay1;
        private static String choice;
        private static boolean n;
        private static String False;
        private static boolean y;
     
     
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
     
            //format number and currency
           NumberFormat NF = NumberFormat.getCurrencyInstance();
     
     
            double months;
            double numyears;
            double loanamount;
            double rate;
            double monthlypay1;
            String choice = "y";
            double calc1;
            double calc2;
            double calc3;
            double calc4;
     
     
     
     
          while (choice.equals("y")) {
     
    try {
            //prompt loan amount
            loanamount=0;
            rate = 0;
            numyears = 0;
     
     
            System.out.print("Enter Loan Amount:");                           
            loanamount = Double.parseDouble(in.nextLine());
     
            //prompt rate
            System.out.print("Enter Rate:");
             rate = Double.parseDouble(in.nextLine());
     
     
             //prompt years
            System.out.print("Enter Number of Years:");
            numyears = Double.parseDouble(in.nextLine());
     
            rate = rate / 12 / 100;
            months = 12 * numyears;
     
     
          //calculation monthly
            calc1 = loanamount * rate;
            calc2 = (Math.pow (1 + rate, months));
            calc3 = (calc2 -1);
            calc4 = (calc2 / calc3);
     
            monthlypay1 = loanamount * rate * calc4;
     
     
     
             if ((loanamount > 0 && rate > 0) && numyears > 0 ) {
                System.out.println("The Monthly Payment is:" + NF.format (monthlypay1));  
                } else { 
                 System.out.println("You need to enter positive numerical data!");
     
             }
                break;
     
    }
     
            while (monthlypay1 < 0) {
                System.out.print("You need to enter positive numerical data!");
                break;
     
     
             }
                System.out.print("");
                System.out.print("Would you like to continue calculations( y / n)?");
     
                choice  = in.nextLine();
     
     
               catch (Exception e) {
                   }
           }
        }
    }


  2. #2
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Catch without a try error

    You need to have a try block before the catch. The try block is where an exception might occur and the catch blocks tell what to do if certain exceptions occur.

    You only have a catch block. You need both a try and a catch block or else you will get a compiler error.

    There can't be any code between the try and the catch blocks.

    It's similar to what happens if you don't have brackets and have an if/statement with more than one line of code after the if and before the else.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Catch without a try error

    If you don't understand my answer, don't ignore it, ask a question.

  4. The Following User Says Thank You to Norm For This Useful Post:

    Ancharius (October 29th, 2013)

  5. #4
    Member
    Join Date
    Oct 2013
    Posts
    31
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Catch without a try error

    Thanks alot guys. I will look at the tutorial. And My java teacher told me to put everything within the try block to make it more simple. Because it will try through everything and catch any error at the end.

  6. #5
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Catch without a try error

    That is the simplest solution. As you get more experienced you should only place code that can throw an exception inside the try block.
    Improving the world one idiot at a time!

  7. #6
    Member
    Join Date
    Oct 2013
    Posts
    31
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Catch without a try error

    Ok i fixed the error's of catch without a try and vice versa. But now its telling me that my variable "monthlypay1" is not initialized which I don't understand how it isn't. Otherwise the code wouldn't work at the beginning...
    The error is occurring at the last while statement.
    package monthypayment2;
    import java.text.NumberFormat;
    import java.util.Scanner;
     
     
    public class Monthypayment2 {
        private static double monthlypay1;
        private static String choice;
        private static boolean n;
        private static String False;
        private static boolean y;
     
     
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
     
            //format number and currency
           NumberFormat NF = NumberFormat.getCurrencyInstance();
     
     
            double months;
            double numyears;
            double loanamount;
            double rate;
            double monthlypay1;
            String choice = "y";
            double calc1;
            double calc2;
            double calc3;
            double calc4;
     
     
     
     
          while (choice.equals("y")) {
     
     try {
            //prompt loan amount
            loanamount=0;
            rate = 0;
            numyears = 0;
     
     
            System.out.print("Enter Loan Amount:");                           
            loanamount = Double.parseDouble(in.nextLine());
     
            //prompt rate
            System.out.print("Enter Rate:");
             rate = Double.parseDouble(in.nextLine());
     
     
             //prompt years
            System.out.print("Enter Number of Years:");
            numyears = Double.parseDouble(in.nextLine());
     
            rate = rate / 12 / 100;
            months = 12 * numyears;
     
     
          //calculation monthly
            calc1 = loanamount * rate;
            calc2 = (Math.pow (1 + rate, months));
            calc3 = (calc2 -1);
            calc4 = (calc2 / calc3);
     
            monthlypay1 = loanamount * rate * calc4;
     
     
     
             if ((loanamount > 0 && rate > 0) && numyears > 0 ) {
                System.out.println("The Monthly Payment is:" + NF.format (monthlypay1));  
                } else { 
                 System.out.println("You need to enter positive numerical data!");
     
             }
                break;
     
           } catch (Exception e ) {
           }
     
           [B] while (monthlypay1 < 0) [/B]{
                System.out.print("You need to enter positive numerical data!");
                break;
     
     
             }
                System.out.print("");
                System.out.print("Would you like to continue calculations( y / n)?");
     
                choice  = in.nextLine();
     
     
        }
    }
    }

  8. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Catch without a try error

    my variable "monthlypay1" is not initialized
    Which one? I see two variables with that name.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #8
    Member
    Join Date
    Oct 2013
    Posts
    31
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Catch without a try error

    The one at the bottom.
    while (monthlypay1 < 0) {
                System.out.print("You need to enter positive numerical data!");
                break;
     
     
             }
                System.out.print("");
                System.out.print("Would you like to continue calculations( y / n)?");
     
                choice  = in.nextLine();
    So that little bit. I can't seem to find what's wrong with it. I've tried just retyping it cause sometimes I make errors via the name.
    I can't move it obviously because of how the loop works.

  10. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Catch without a try error

    Why are there two variables with the same name? That is often a problem. Change the name of one of them so their names are different.
    If you don't understand my answer, don't ignore it, ask a question.

  11. The Following 2 Users Say Thank You to Norm For This Useful Post:

    Ancharius (October 30th, 2013), aussiemcgr (October 30th, 2013)

  12. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Catch without a try error

    What Norm said is correct. A little thing called: "scope" hides variables. When code is executed, it looks for variable names in the closest scope. You have declared monthlypay1 as a class instance variable, but you have declared another variable with the same name in your main. Because of this, any reference to monthlypay1 in your main after the declaration will refer to the variable which only exists in your main, not your class instance variable. If you use Eclipse as your IDE, you can set it to warn you about variable hiding (other IDEs probably can as well, but I don't know how to set them up).

    Continuing on with that thought, variables declared inside of a method are not automatically given default values (whereas variables declared as class instance variables are). This includes primitives, like doubles. So the error you are getting is occurring because you did not initialize the monthlypay1 variable declared in your main method. But, the bigger problem, as Norm pointed out, is you variable hiding.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  13. The Following 2 Users Say Thank You to aussiemcgr For This Useful Post:

    Ancharius (October 30th, 2013), Norm (October 30th, 2013)

  14. #11
    Member
    Join Date
    Oct 2013
    Posts
    31
    Thanks
    10
    Thanked 0 Times in 0 Posts

    Default Re: Catch without a try error

    Thanks guys I fixed it in class today. I had to set my double monthlypay1=0; and that made it work. As for the hiding my variable's I'll fix that up so my variables aren't hiding. But thanks for everything.
    topic solved. and program works.

Similar Threads

  1. Try and catch
    By jaydac12 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 10th, 2013, 05:58 AM
  2. try-catch block reports to have an Error that I don't know how to fix
    By baraka.programmer in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 24th, 2011, 06:27 AM
  3. logic error somewhere.. working with try & catch, simple array.. please help
    By basketball8533 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 9th, 2010, 12:40 PM
  4. catch all
    By silverspoon34 in forum Exceptions
    Replies: 1
    Last Post: November 29th, 2009, 02:18 PM
  5. try/catch
    By rsala004 in forum Exceptions
    Replies: 5
    Last Post: July 19th, 2009, 03:20 PM

Tags for this Thread