Look in the API to see if a method throws an Exception. For example, this constructor of the Scanner class:
[url]http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#Scanner(java.io.File)[/url]
Throws a FileNotFoundException.
try
{
Scanner s = new Scanner(new File("asdf.txt"));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
hi,
if you want a general try catch block which can handle any exception then do the following thing.
//--
try{
// some code
}
catch (Exception e) {
e.printStackTrace();
}
//--
this can catch any exception because "Exception" is the super class of all exception classes( i.e, IOException, FileNotFoundException, SQLException etc).
but i think you should use specific exception handling. because
if you are trying to create a file in wrong directory, then you may want to handle ( suppose to show a specifice msg) it one way. and for failing to write into a file, want to show a different msg.
for this purpose you need to do the specific exection handling.
try
{
f = new RandomAccessFile("a.txt", "rw");
f.write(10);
}
catch (FileNotFoundException ex)
{
System.out.println("can not create file.");
}
catch (IOException ex1)
{
System.out.println("unable to write into file");
}
you can see the api documentation to know which methods throws which exception.