throw new error java 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: java throw an exception
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a number");
try {
double nb1 = kb.nextDouble();
if(nb1<0)
throw new ArithmeticException();
else System.out.println( "result : " + Math.sqrt(nb1) );
} catch (ArithmeticException e) {
System.out.println("You tried an impossible sqrt");
}
}