i read that a method that is is using throws clause must be mentioned in the try and catch block.So when we use "throws IOException" in the following program why dont we use try and catch

import java.io.*;
class testthrows
{
public static void main(String args[]) //throws IOException
{
int i;
System.out.println("enter a number");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=Integer.parseInt(br.readLine());
System.out.println(i);
}
}

why dont we use try and catch here

A try catch block is necessary if you want to handle the exception. If you don't want to handle the exception, you can announce the fact through a throws clause appended to the method. The calling method then has to take care or pass it up the hierarchy. In your code you are passing the exception to the jvm which calls the main method

In this case you are relying on the JVM to catch the exception when your main(..) method throws it, presumably because the JVM's default processing (print out the details of the Exception to System.err and terminate the program) is good enough.
In general you would put the IO method calls inside a try/catch so you can decide exactly what to do - eg show the user a standard error dialog box

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.