Throw keyword in java
- Throw keyword is used to throw exception manually.
- Whenever it is required to suspend the execution of the functionality based on the user defined logical error condition we will use this throw keyword to throw exception.
- So we need to handle these exceptions also using try catch blocks.
Java simple example Program to explain use of throw keyword in java
- package exceptions;
- public class ThrowKeyword {
- public static void main(String[] args) {
- try {
- throw new ArithmeticException();
- } catch (Exception e) {
- System.out.println(e);
- e.printStackTrace();
- }
- }
- }
Output:
- java.lang.ArithmeticException
- java.lang.ArithmeticException
- at exceptions.ThrowKeyword.main(ThrowKeyword.java:11)
Rules to use "throw" keyword in java
- throw keyword must follow Throwable type of object.
- It must be used only in method logic.
- Since it is a transfer statement , we can not place statements after throw statement. It leads to compile time error Unreachable code
- We can throw user defined exception using throw keyword.
- //Custom exception
- package com.instanceofjavaforus;
- public class InvalidAgeException extends Exception {
- InvaidAgeException(String msg){
- super(msg);
- }
- }
- package com.exceptions;
- public class ThrowDemo {
- public boolean isValidForVote(int age){
- try{
- if(age<18){
- throw new InvalidAgeException ("Invalid age for voting");
- }
- }catch(Exception e){
- System.out.println(e);
- }
- return false;
- }
- public static void main(String agrs[]){
- ThrowDemo obj= new ThrowDemo();
- obj.isValidForVote(17);
- }
- }
Output:
- exceptions.InvalidAgeException: Invalid age for voting
- We can throw predefined exceptions using throw keyword
- package com.instanceofjava;
- public class ThrowKeyword{
- public void method(){
- try{
- throw new NullPointerException("Invalid age for voting");
- }
- }catch(Exception e){
- System.out.println(e);
- }
- }
- public static void main(String agrs[]){
- ThrowKeyword obj= new ThrowKeyword();
- obj.method();
- }
- }
Output:
- java.lang.NullPointerException: Invalid age for voting
Bagikan
throw keyword in java with example
4/
5
Oleh
Kris Kimcil