Home > Software engineering >  how to use throws Exception?
how to use throws Exception?

Time:01-18

this is my class Person() method inputPersonInfo():

        Scanner sc = new Scanner(System.in);
        System.out.println("Input Information of Person");
        System.out.println("Please input name");
        name = checkInputString();
        System.out.println("Please input address");
        address = checkInputString();
        System.out.println("Please input salary");
        salary = checkInputSalary();        
        return new Person(name,address,salary);
        
        }

this is my check for input method:

    public static String checkInputString() {
       //loop until user input true value
        while (true) {
            String s = in.nextLine();
            if (s.isEmpty()) {
                System.err.println("Not empty.");
            } else {
                return s;
            }
        }
    }
    // check if salary is smaller than 0
    public static double checkInputSalary() {
       //loop until user input true value        
        while (true) {
            try {
                double salary = Double.parseDouble(in.nextLine());
                if (salary < 0) {
                    System.err.println("Salary is greater than zero");
                    System.out.print("Please input salary: ");
                } else {
                    return salary;
                }
            } catch (NumberFormatException ex) {
                System.err.println("You must input digidt.");
                System.out.print("Please input salary: ");
            }
        }
    }

how can i throws Exception in this method without using the above checkinput method() ?

public Person inputPersonInfo (String name, String address, Double salary) throws Exception {} 

this is my main class(), do i need to throw any Exception in my main class ?:

        
        System.out.println("=====Management Person programer=====");        
        
        //call constructor Person
        Person p = new Person(); 
        //enter 3 person 
        for (int i =0; i< 3 ;i  ){           
           persons[i] = p.inputPersonInfo(p.getName(), p.getAddress(), p.getSalary());
        }

CodePudding user response:

throws Exception is used when defining a method to signal that this method may throw an error in case something does not go right. It is simply a signal, it does not handle anything.

In case you add this to a method declaration, wherever you call this method, you will be required (by the IDE, compiler..) to add handling mechanisms, such as a try-catch clause, or add yet another throws Exception to the declaration of the method that is calling your "dangerous" method.

Example:

public void dangerousMethod() throws Exception, RuntimeException // Or whatever other exception
{
    throw new Exception("FAKE BUT DANGEROUS");
}
public void anotherMethod()
{
    dangerousMethod(); // <------------ Compiler, IDE will complain that this should be handled in some way
    
    
    // Either add try catch:
    
    try
    {
        dangerousMethod();
    }
    catch(Exception e) // Or whatever specific Exception you have
    {
        // Handle it...
    }
    
    
    // Or add the throws Exception at the head of the anotherMethod()
}

CodePudding user response:

For unchecked exception:

NumberFormatException is a RuntimeException, which is an "unchecked exception", that means even if you don't try...catch it, it will eventually thrown to the outside (the caller).

In the outside (the caller), you can try...catch it if you want so, or you can ignore it. If the exception happens, it will be thrown out. If your program is a console program, it will be thrown and displays in the console window.

That also means your main method don't have to explicitly try..catch or throws it, and the compiler will still compile it successfully.

For checked exception:

On the other side, about the "checked exception", you have to try..catch or else the compiler will show you errors. If you do not want to try...catch the exception in the current method, you can use throws Exception in the method signature. For e.g with IOException:

public Person inputPersonInfo (String name, String address, Double salary) throws IOException {}

In your main method that is calling the above inputPersonInfo(), you have to try..catch or throws it in the main method signature.

For e.g: with IOException (a checked exception)

public static void main(String[] args) throws IOException {
    ...
    inputPersonInfo(...);
    ...
}

CodePudding user response:

Create the method so that Exceptions won't be thrown to begin with:

public double getSalaryFromUser() {
    String salary = "";
    while (salary.isEmpty()) {
        System.out.print("Please enter a Salary amount: --> ");
        salary = in.nextLine();
        /* Input Validation:
           The RegEx below used as argument for  the String#matches() 
           method checks to see if the supplied string is a unsigned
           Integer or floating point numerical value. If anything other 
           than that is supplied then the error message is displayed. 
           The second condition checks to see if the value is greater 
           than 0.9d             */ 
        if (!salary.matches("\\d (\\.\\d )?") || Double.valueOf(salary) < 1.0d) {
            System.out.println("Invalid Entry ("   salary   ")! You must supply a");
            System.out.println("numerical value and it must be greater than zero.");
            System.out.println("Try again...");
            System.out.println();
            salary = "";
        }
    }
    return Double.parseDouble(salary);
}
  •  Tags:  
  • Related