When to throw an exception? When to try and catch and exception.
What does Throwing an exception mean?
How can I throw a general exception in Java? - Stack Overflow
java - Why is "throws Exception" necessary when calling a function? - Stack Overflow
Videos
Hello, I am lookign for a clear example of when you throw an exception and how to use it do you catch that thrown exception somewhere or does it end there. When do you use try and catch block for exceptions? I understand the concept of exceptions but that part isn't very clear to me. One method throws it other method catches it and so on.
I understand try, catch, and finally. But what does throw mean and how would i use it?
You could create your own Exception class:
public class InvalidSpeedException extends Exception {
public InvalidSpeedException(String message){
super(message);
}
}
In your code:
throw new InvalidSpeedException("TOO HIGH");
You could use IllegalArgumentException:
public void speedDown(int decrement)
{
if(speed - decrement < 0){
throw new IllegalArgumentException("Final speed can not be less than zero");
}else{
speed -= decrement;
}
}
In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.
From Java Tutorial:
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?
Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.
Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:
Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an
ArithmeticExceptionof division by zero occurs or anArrayIndexOutOfBoundsExceptionoccurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.Errors: Errors are situations from which usually the program cannot recover. For example, if a
StackOverflowErroroccurs, our program cannot do much, such as increase the size of program's function calling stack. Or if anOutOfMemoryErroroccurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.
For detailed information see:
- Unchecked Exceptions — The Controversy
- The Catch or Specify Requirement
Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.
For example:
class throwseg1 {
void show() throws Exception {
throw new Exception();
}
}
Should be written as:
class throwseg1 {
void show() {
try {
throw new Exception();
} catch(Exception e) {
// code to handle the exception
}
}
}
This way you can get rid of the "throws Exception" declaration in the method declaration.
new Exception() means create an instance (same as creating new Integer(...))
but no exception will happen until you throw it...
Consider following snippet:
public static void main(String[] args) throws Exception {
foo(1);
foo2(1);
}
private static void foo2(final int number) throws Exception {
Exception ex;
if (number < 0) {
ex = new Exception("No negative number please!");
// throw ex; //nothing happens until you throw it
}
}
private static void foo(final int number) throws Exception {
if (number < 0) {
throw new Exception("No negative number please!");
}
}
the method foo() will THROW an exception if the parameter is negative but the method foo2() will create an instance of exception if the parameter is negative
Exception e = new Exception ();
Just creates a new Exception, which you could later throw. Using
throw e;
Whereas
throw new Exception()
Creates and throws the exception in one line
To create and throw a runtime exception
throw new RuntimeException()