Java - how should a method with return treat exceptions -



Java - how should a method with return treat exceptions -

i'm doing exercises exception handling , nil working. i'd know how method homecoming should implement exception, instance:

public class class{ double n1, n2, result; public double sum(double n1, double n2){ this.n1 = n1; this.n2 = n2; result = n1 + n2; homecoming result; } }

this b e class , method, then..what if want create exception makes sure no letters input (the scanner in main class).

i tried next code:

public double sum(double n1, double n2){

try{ this.n1 = n1; this.n2 = n2; result = n1 + n2; }catch(numberformatexception e){ system.out.println("error!"); homecoming 0; } homecoming result; }

but whenever execute , input letter, next error occurs:

exception in thread "main" java.util.inputmismatchexception @ java.util.scanner.throwfor(scanner.java:909) @ java.util.scanner.next(scanner.java:1530) @ java.util.scanner.nextdouble(scanner.java:2456) @ lista05excecoes.principal.main(principal.java:17) java result: 1

when wanted output message error

the code have shown isn't responsible throwing exception; can calculate sum.

from stack trace, main method contains code throws exception, using scanner. scanner found non-numeric input , threw exception. place try/catch block around nextdouble method, not code sums 2 numbers.

java exception methods

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -