Java IO Exceptions

 

IO-Exception Handling

1)  Read the code below carefully.

import java.io.*;

public class OutOut
{
 public static void main(String args[]) throws IOException
 {
  PrintStream pr = new PrintStream(new FileOutputStream("outfile"));

  System.out = pr;

  System.out.println("Lets see what I see now??");
 }
}

  1. The code causes a compiler error. out is a declared final in System and cannot be assigned to pr.
  2. The code causes a runtime Exception due the assignment to a final variable.
  3. The code compiles and runs success fully.  A file called "outfile" is created and "Lets see what I see now??" is printed in the same.

2)  Is the following code legal?

1.  try {
2.      
3.  } finally {
4.      
5.  }

3)What exception types can be caught by the following handler?

6.  catch (Exception e) {
7.       
8.  }-----------All Type of Exception it will handle

What is wrong with using this type of exception handler?

4) Is there anything wrong with the following exception handler as written? Will this code compile?

9.  try {
10. 
11.} catch (Exception e) {
12.    
13.} catch (ArithmeticException a) {
14.    
15.}
 

5)Match each situation in the first list with an item in the second list.

    1. int[] A;
      A[0] = 0;
      3
    2. The JVM starts running your program, but the JVM can't find the Java platform classes. (The Java platform classes reside in classes.zip or rt.jar.)1
    3. A program is reading a stream and reaches the end of stream marker.
    4. Before closing the stream and after reaching the end of stream marker, a 4
    5. program tries to read the stream again. 2

1__error

2_checked exception

3__compile error

4__no exception

6) What is an Error (as opposed to an Exception)?

7) What is the difference between a checked and unchecked exception?

 

Ans-Checked  are IOException are checked Exception

 

Unchecked Exception- Error and Runtime Exception

Not necessary to specify in the clause.

 

 

 

 

Q8)

What is the result when you compile and run the following code?

 
public class ThrowsDemo 
{ 
    static void throwMethod()
    { 
        System.out.println("Inside throwMethod."); 
        throw new IllegalAccessException("demo"); 

    }

    public static void main(String args[]) 
    { 
        try
        { 
            throwMethod(); 
        }
        catch (IllegalAccessException e)
        { 
            System.out.println("Caught " + e); 
        } 
    } 
} // ThrowsDemo

 

 

(1)

Compilation error

(2)

Runtime error

(3)

Compile successfully, nothing is printed

(4)

Inside throwMethod. followed by caught: java.lang.IllegalAccessExcption: demo