What will be output?
- public class MindGame {
- public static void main(String[] args) {
- Float a=0;
- try{
- System.out.println(a/0);
- }catch(Exception e){
- System.out.println("Error");
- }
- catch(IOException e1){
- System.out.println("Error1");
- }}
output-
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Type mismatch: cannot convert from int to Float
Unreachable catch block for IOException. It is already handled by the catch block for Exception
at MindGame.main(MindGame.java:6)
Here we can see three errors
1.declaration of float a, we should assign it as 0.0
2.in catch block- as we know that we can use more than one catch block for one try block in Java but keep in mind "we cant use superclass exception in 1st catch block, here keep superclass exception in 1st catch block and superclass into 2nd catch block,"
After modification of programme
- public class MindGame {
- public static void main(String[] args) {
- Float a=0.0f;
- try{
- System.out.println(a/0);
- }catch(IOException e){
- System.out.println("Error");
- }
- catch(Exception e1){
- System.out.println("Error1");
- }
- }}
Here error is IOexception is never thrown from the try block, exception must be specific or use only Exception class.
Again after modification
- public class MindGame {
- public static void main(String[] args) {
- Float a=0.0f;
- try{
- System.out.println(a/0);
- }catch(ArithmeticException e){
- System.out.println("Error");
- }
- catch(Exception e1){
- System.out.println("Error1");
- }
- }}
now we can get successful result and result will be NaN, now think why we got this result
Reason is here-"NaN" stands for "not a number". "Nan" is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined. Taking the square root of a negative number is also undefined.
Whats about this
- public class MindGame {
- public static void main(String[] args) {
- Float a=0.0f;
- try{
- System.out.println(a/0.0);
- }catch(ArithmeticException e){
- System.out.println("Error");
- }
- catch(Exception e1){
- System.out.println("Error1");
- }
- }}
In line number 3 dividing from 0.0 then output will be same.
Thanks
Keep Happy Learning.. :)
No comments:
Post a Comment