try/catch
we are supposed to use the most appropriate exception in the catch clause.
for example
try{
FileInputStream fin = new FileInputStream("A.java");
}catch(FileNotFoundException exp1){
System.out.println("file not found");
}
Why it's NOT advisable to use something like
try{
FileInputStream fin = new FileInputStream("A.java");
}catch(Exception exp1){
System.out.println("file not found");
}
kindly explain.
Ans:
Well the class Exception is much wider than FileNotFoundException, and will catch every subclass of Exception.
One reason people cast the net wide with an overly general catch block is because code may throw several different exceptions:
code:
try {
...
}
catch (ClassNotFoundException e) {...}
catch (InstantiationException e) {...}
catch (IllegalAccessException e) {...}
catch (EtcException e) {...}
don't just catch "Exception" unless you really don't what to know or care what went wrong.
for example
try{
FileInputStream fin = new FileInputStream("A.java");
}catch(FileNotFoundException exp1){
System.out.println("file not found");
}
Why it's NOT advisable to use something like
try{
FileInputStream fin = new FileInputStream("A.java");
}catch(Exception exp1){
System.out.println("file not found");
}
kindly explain.
Ans:
Well the class Exception is much wider than FileNotFoundException, and will catch every subclass of Exception.
One reason people cast the net wide with an overly general catch block is because code may throw several different exceptions:
code:
try {
...
}
catch (ClassNotFoundException e) {...}
catch (InstantiationException e) {...}
catch (IllegalAccessException e) {...}
catch (EtcException e) {...}
don't just catch "Exception" unless you really don't what to know or care what went wrong.
0 Comments:
Post a Comment
<< Home