The program given below is will help you understanding of exception handling of java and also helpful for SCJP examination.
The program given below is will help you understanding of exception handling of java and also helpful for SCJP examination.1 .public class Question3{
2 .public static void main(String[] args) {
3 .try {
4 .int a= (int)(Math.random()*5);
5 .if(a<=2.5)
6 .System.out.println("a="+a);
7 .else
8 .throw new Exception("a>2.5");
9. } catch (Exception e){
10. System.err.println(e.getMessage() );
11. System.err.println("Value of a="+a);
12. } } }
Find the output of the following code :
1.An Exception is raised during compilation.
2.An Exception is thrown at run time.
3.Unresolved compilation problem.
4.a=2 or a=1 or i >2.5 Value of i =null
(3)
Explanation :
This code will not compile because variable "a" at line number 11 , is not recognize by compiler since "a" is a local variable declared inside "Try" block. This code can be corrected by applying code line "static String a = null ;"at line number2(or immediately after declaration of class & before 'main( )').