java raise exception code example
Example 1: python raise exception
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
Example 2: raise error java
throw new java.lang.Error("this is very bad");
throw new java.lang.RuntimeException("this is not quite as bad");
Example 3: java how to throw exception
public class ThrowException{
public static void main(String [] args) throws Exception{
//throws Exception line is needed if not using try-catch block
throw new Exception("Errmessage");
}
}
Example 4: throwing exceptions java
/* In this program we are checking the Student age
* if the student age<12 and weight <40 then our program
* should return that the student is not eligible for registration.
*/
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 5: exception in java
In java exception is an object. Exceptions are created when an abnormal
situations are arised in our program. Exceptions can be created by JVM or
by our application code. All Exception classes are defined in java.lang.
In otherwords we can say Exception as run time error. I use try & catch blocks
to handle any exceptions in my code.
I am familiar with major checked and unchecked exceptions and
handle it accordingly to make my code execution smooth
Example 6: 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");
}
}