You can't catch an exception if you haven't thrown something. That was the reason I was required to add throws in the readSomething() method.
throw - This is used to throw an exception and it requries an object of Exception.
throws - This works like the throw above but this is used after the method parameters as an extension when your method get an exception. Since this works like an extension, you can separate different exception with a comma.
void readFile(String name) throws IOException, IndexOutOfBoundsException{ // block }
But the difference is when you use throws, the program will stop right away in there and won't process the others while throw, you can use a catch and let the process continue.
=================
class PracticeThrow{
public static void main(String[] args){
PracticeThrow.dividingNumbersRev(6, 2);
PracticeThrow.dividingNumbers(6, 0);
}
private static void dividingNumbers(int x, int y){
try{
if(y == 0){
throw new AritmeticException();
}else {
System.out.println("answer: " + (x/y));
}
}catch(ArithmeticException e){
System.out.println("Error: " + e.fillInStrackTrace());
}
}
private static void dividingNumbersRev(int x, int y) throws ArithmeticException{
System.out.println("answerRev: " + (x/y));
}
}
================
Result:
answerRev: 3
Erro: java.lang.ArithmeticException
Note: Stack trace is a list of information about the classes and methods called before the error occurs. Is possible for an exception to have another exception that it chains. You can use the Throwable class to check for the cause. There are some advantages when you used exceptions but I don't want to go through that.
YOU ARE READING
Java Programming
Randomhttps://docs.oracle.com/javase/tutorial/ This is the link where I learned my java lessons online. I choose java as first programming language. I am a career shifter. I just want to start something new. I choose to write it here in Wattpad so that I...