views:

736

answers:

10

I'm a Java beginner so please bear with me :P

static int load = 100;
static int greet;

public void loadDeduct(int cLoad, int c){
    int balance;
    balance = cLoad - 7;
    System.out.println("Your balance: " + balance);
}

public void loadDeduct(int tLoad){
    int balance;
    balance = tLoad - 1;
    System.out.println("Your balance is: " + balance);
}

public static void main (String [] args){
    int choice;
    Scanner scan = new Scanner(System.in);

    System.out.println("I'm a cellphone, what do you want to do?");
    System.out.println("Press 1 to send SMS / Press 2 to Call");

    choice = scan.nextInt();

    CellphoneLoad N95 = new CellphoneLoad();

    if (choice == 1){
        N95.loadDeduct(load);
    }else if (choice == 2){
        N95.loadDeduct(load, greet);
    }else{
        System.out.println("Invalid Option!!!");
    }

How do I implement the exception handling with this program? I'm not quite sure how to use the catch block as we weren't taught yet about the whole exceptions thing. It was just an exercise we were asked to do. I want to replace the if else statements with a try-catch blocks... is that possible?

A: 

where/why do you want to use exceptions? I don't see any in your code.

cd1
well i want to replace the if else statements with a try-catch blocks... is that possible?
A: 
Charlie Martin
+1  A: 

It is not ideal to use Exceptions for flow control. From your code it is not clear what Exceptions might be thrown. Maybe you can elaborate a bit more.

Patrick
A: 

The only part of your code that might possibly throw an exception is the call to:

scan.nextInt();

According to the JavaDocs, this can throw the following possible exceptions:

  • InputMismatchException (if the next token does not match the Integer regular expression, or is out of range)
  • NoSuchElementException (if input is exhausted)
  • IllegalStateException (if this scanner is closed)

So if you wanted your code to account for the possibilities of these exceptions being thrown, you should re-write it like so:

try {
    choice = scan.nextInt();
} 
catch (InputMismatchException e) {
  System.out.println(e.getMessage());
}
catch (NoSuchElementException e) {
  System.out.println(e.getMessage());
}
catch (IllegalStateException e) {
  System.out.println(e.getMessage());
}

Generally, you want your "catch" blocks to start out specific or very likely to happen to less likely / more general in nature.

You can additionally "throw" the exceptions so that whatever method the exception occurs in doesn't handle it-- the method which called that exception-causing method would have to handle it (or throw it again, etc, until it gets to the Java runtime).

In the event it's the "if" statement you wish to replace, I'd recommend the "switch" statement:

switch (choice) {
    case 1:  N95.loadDeduct(load);
             break;
    case 2:  N95.loadDeduct(load, greet);
             break;
    default: System.out.println("Invalid Option!!!");
}
Cuga
A: 

I don't see any reason to use exceptions instead of the if-else block. you could try using a switch statement, it'd look better.

you should use exceptions to handle errors that might occur inside the methods loadDeduct. then you would surround the lines calling N95.loadDeduct with a try-catch block, to write what would happen if loadDeduct went wrong.

cd1
+1  A: 

The Scanner.nextInt() method can throw a few exceptions. The linked page of the API Specifications lists out the three exceptions which can be thrown.

For example, if a non-integer value is entered, such as "one" instead of 1, an InputMismatchException can be thrown.

In general, a try-catch is used to catch exceptions, as illustrated in the following code:

try
{
    Integer.parseInt("one");      // Statement that can cause an exception.
}
catch (NumberFormatException e)   // Specify which exception to catch.
{
    // Code to handle the NumberFormatException.
}

More information about exceptions can be found in Lessons: Exceptions of The Java Tutorials. In particular, the Catching and Handling Exceptions section may be useful.

coobird
+1  A: 

One important principle to consider with exceptions in Java is that there are two types: 1. Runtime 2. Typed/explicit (for lack of a better word)

Runtime exceptions should be thrown when there is a programming error and generally they should not be caught unless you are catching at the top level to report an error.

Typed/Explicit exceptions are decorated on method calls and should be there so the caller can take some action on them.

In the case of the code above, there isn't really a place that feels like it should use exception handling.

And as Patrick pointed out, you don't generally want to use exceptions for flow control.

GreenKiwi
+1  A: 

Adding exceptions in this piece of code does not add much value. What I can think of is something like this:

public static void main (String [] args){

.....

try{
 handleUserChoice(choice);//new method
}
catch(InvalidChoiceException e){
 System.out.println("Invalid Option!!!");
}
}
svachon
A: 

I actually have another question. I tried using an IllegalArgumentException to catch other options aside from integers 1&2, and I tried using an InputMismatchException in case the user enters non-integers.

The InputMismatch Exception doesn't seem to be working.

here's the try block :

   try {
      if (choice == 1) {
     N95.loadDeduct (load, greet);
      } else if (choice == 2) {
        N95.loadDeduct(load); 
      } 
    }

here are the catch blocks:

    catch (InputMismatchException e) {
  System.out.println("Please enter only numbers.");
 }
 catch (IllegalArgumentException e) {
  System.out.println("You have entered an invalid option. Please choose only from the two choices provided.");
 }

I haven't forgotten to import InputMismatchException from util either.

import java.util.InputMismatchException;
A: 

Hi, Im having one class that contains 100 methods.I need to generate try catch block automatically to those methods for eg:100 methods means need 100 try catch block. i want to generate this try catch block automatically to all those methods.