-
Exception handdling
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter your first Number");
int a = obj.nextInt();
System.out.println("Enter Your Second Number");
int b = obj.nextInt();
int sum = a / b;
System.out.println(sum);
throws BadNumberException{
if(b==0){
throws new BadNumberException("cannot divide by zero");
}
}
}
}
in the above code the bold text are wrong how to correct them
-
It's 'throw' not 'throws'; check any Java text book for the syntax.
kind regards,
Jos
-
spoon-feeding )
Code:
import java.util.Scanner;
class BadNumberException extends Exception {
public BadNumberException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) throws Exception {
Scanner obj = new Scanner(System.in);
System.out.println("Enter your first Number");
int a = obj.nextInt();
System.out.println("Enter Your Second Number");
int b = obj.nextInt();
if(b==0) {
throw new BadNumberException("cannot divide by zero");
}
int sum = a / b;
System.out.println(sum);
}
}
-
Correct code
Hi
First of all your syntax is wrong for throws it is as follows
Syntax: return-type method-name(parameters-list) throws exception-list{
body of method
}
Complete and Running code is as follows
__________________________________________________ ______________
import java.util.Scanner;
class BadNumberException extends Exception{
public BadNumberException(String message){
super(message);
}
}
public class Main {
public static void main(String[] args) {
try{
Scanner obj = new Scanner(System.in);
System.out.println("Enter your first Number");
int a = obj.nextInt();
System.out.println("Enter Your Second Number");
int b = obj.nextInt();
if(b==0){
throw new BadNumberException("cannot divide by zero");
}
else{
int sum = a / b;
System.out.println("Result is : "+sum);
}
}catch(BadNumberException e){
System.out.println(e.getMessage());
}
}
}
__________________________________________________ ____________