I am currently learning about exception handling in my java class and have a question that I can't seem to find a clear answer on. I'm sure that the answer is something very simple that I am somehow overlooking, otherwise it wouldn't be included as part of the language.
I can't seem to understand the purpose of throwing an exception. In the programs I've been dealing with, the catch block automatically catches the exception if the try block doesn't work...so why would I need to throw an exception if the catch block will automatically catch the exception anyway?
Kody Wright wrote:...why would I need to throw an exception if the catch block will automatically catch the exception anyway?
One thing to consider is that try/catch blocks allow you to separate unusual circumstances (exceptions) from the rest of your code. Throwing an exception is a way of saying, "I need to break out of the regular process because something unusual happened."
Another thing to consider is that catch statements can be very specific in the types of exceptions they catch. You might be used to seeing catch(Exception e), which will catch any type of Exception (including its subtypes). This might have you thinking that all exceptions end up getting caught (handled) in the same place. But, for example, catch(IOException e) will only catch an IOException (and its subtypes). So being more specific in the type of Exceptions caught allows your code to throw different types of exceptions to be handled differently in different catch blocks.
There are situations where you have to create new exceptions specific to your application. In those cases, you simply extend the Exception class and create your custom exception. Furthermore, you may find a situation where your application could crash due to some known reason, in that case you could throw an exception that encapsulates that problem and handle it.