Hello Poonam
Like playing catch with a ball, programming involves trowing and catching exceptions. An exception is normally some problem that needs to be "fixed" by the programmer. But this means that we need to do more work. So here throwing comes in. If you do some logical test and you find that something funny is happening then you can "throw" an Exception instance. For example:
int a = 1, b = 0;
if (b != 0){
// cool!
int c = a / b;
} else {
// Darn it.
throw new Exception("Can't devide by zero!");
}
To catch it you use an try-catch block. Look at this method:
public static void go(){
try{
int a = 1, b = 0;
if (b != 0){
// cool!
int c = a / b;
} else {
// Darn it.
throw new Exception("Can't devide by zero!");
}
} catch (Exception e) {
// Gotcha ha!
System.out.println(e.getMessage());
}
}
This means that you need to catch and handle the exception. Exceptions are not fun to work with, so you can pass it on the the user of your methods. Although, this is not very nice, but it can speed up your developing time. To "pass on" exceptions to the user of your method, you use the throws keyword:
public static void go() throws Exception{
int a = 1, b = 0;
if (b != 0){
// cool!
int c = a / b;
} else {
// Darn it.
throw new Exception("Can't devide by zero!");
}
}
The problem is that the user of this method must now worry about this:
try{
go();
} catch (Exception e) {
// Gotcha ha!
System.out.println(e.getMessage());
}
It is possible to keep throwing an Exception, but it is not a very good way to program. The best way to handle exceptions, is as early as possible!
I hope this helped you.
