Exception handdling

• 02-19-2011, 03:53 PM
vibaviattigala
Exception handdling
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner obj = new Scanner(System.in);

int a = obj.nextInt();
int b = obj.nextInt();
int sum = a / b;
System.out.println(sum);
if(b==0){
throws new BadNumberException("cannot divide by zero");

}

}

}
}
in the above code the bold text are wrong how to correct them
• 02-19-2011, 04:25 PM
JosAH
It's 'throw' not 'throws'; check any Java text book for the syntax.

kind regards,

Jos
• 02-19-2011, 04:32 PM
Petr
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);     } }```
• 02-19-2011, 05:08 PM
sandeeptheviper
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;

super(message);
}
}

public class Main {
public static void main(String[] args) {
try{
Scanner obj = new Scanner(System.in);
int a = obj.nextInt();
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);
}