java how to throw an exception code example
Example 1: throw io exception java
public static void foo() throws IOException {
throw new IOException("error message");
}
public static void main(String[] args) {
try {
foo();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Example 2: java how to throw exception
public class ThrowException{
public static void main(String [] args) throws Exception{
throw new Exception("Errmessage");
}
}
Example 3: throwing exceptions java
public class ThrowExample {
static void checkEligibilty(int stuage, int stuweight){
if(stuage<12 && stuweight<40) {
throw new ArithmeticException("Student is not eligible for registration");
}
else {
System.out.println("Student Entry is Valid!!");
}
}
public static void main(String args[]){
System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a nice day..");
}
}
Example 4: throw keyword in java
Generally JVM throws the exception and
we handle the exceptions by
using try catch block. But there are
situations where we have to throw
userdefined exceptions or runtime exceptions.
In such case we use throw keyword
to throw exception explicitly.
Syntax : throw throwableInstance;