#
"throw" keyword in Java
This tutorial explains to you how throw
keyword in Java.
#
"throw" keyword in Java - theory
The throws
keyword in Java is used to specify the exceptions (defined by the programmer or a known Java exception) which might be raised in that method.
The throw
keyword in Java is used to raise an exception.
#
"throw" keyword in Java - example
Here it is an example of using throw
keyword :
Exception1.java
public class Exception1 extends Exception {
String message;
Exception1(String message) {
this.message = message;
}
@Override
public String toString() {
return ("Output String from toString : "+ message);
}
}
MainApp.java
class MainApp {
public static void main(String[] args) throws Exception1 {
System.out.println("Before throw.");
if (1 == 1) {
throw new Exception1("My message");
}
System.out.println("After throw.");
}
}
When you run this code you will get:
Before throw.
Exception in thread "main" Output String from toString : My message
at MainApp.main(MainApp.java:7)
Process finished with exit code 1
Info
As you can observe, throw
and throws
keywords work together !