I am having some problems with understanding the differences between checked
and unchecked
exceptions in Java.
- Firstly,
checked
exceptions are supposed to look for abnormalities during compile time. Examples provided in different sources cite database connectivity, file handling as some of them, whileunchecked
exceptions are supposed to look for errors on the programmer's part, like indexing beyond the range of an array, etc.
Shouldn't it be the other way round? I mean, database connectivity is done during run-time, right? Same goes for file-handling. You don't open a file-handle during compile time, so why a possible error on that is looked for during compile-time? On the other hand, indexing an array beyond its range is already done in the program, which can be checked during compile time (if the abnormal index is supplied by user during run-time, then it's okay for it to be a run-time problem). What am I missing here?
2 Secondly, how can RunTimeException
, itself being unchecked
, subclass Exception
, which is checked
? What does this signify?
I found an example in Herbert Schildt's book explaining the usage of checked
exceptions:
class ThrowsDemo {
public static char prompt(String str)
throws java.io.IOException {
System.out.print(str + ": ");
return (char) System.in.read();
}
public static void main(String args[]) {
char ch;
try {
ch = prompt("Enter a letter");
}
catch(java.io.IOException exc) {
System.out.println("I/O exception occurred.");
ch = 'X';
}
System.out.println("You pressed " + ch);
}
}
Is the throws
clause necessary here? Why can't I do it just normally with a try-catch
statement like this (sorry I don't know how to simulate an IO Exception
, so couldn't check it myself!):
class ThrowsDemo {
public static char prompt(String str) {
System.out.print(str + ": ");
return (char) System.in.read();
}
public static void main(String args[]) {
char ch;
try {
ch = prompt("Enter a letter");
}
catch(java.io.IOException exc) {
System.out.println("I/O exception occurred.");
ch = 'X';
}
System.out.println("You pressed " + ch);
}
}