Java throw keyword In Hindi

📔 : Java 🔗

पिछले topics में आपने program में आयी Exceptions को handle करना सीखा। Programing करते समय कई जगह हमें किसी particular condition पर exception generate करनी पड़ जाती है।


Java में throw keyword का use explicitly किसी error को generate करने के लिए किया जाता है। explicitly का मतलब है स्पष्ट रूप से या clearly . क्योंकि कई जगह हमें ऐसी need पड़ जाती हैं जहाँ पर हम अपनी तरफ से भी exception को throw / create कर सकें।

Java throw Syntax

throw new className("Error message"); 

Java throw Example

File : ThrowTest.java

CopyFullscreenClose FullscreenRun
public class ThrowTest {   
   // method to check if person is eligible to vote or not .  
   public static void check_age(int age) {  
      if(age<18) {  
         //throw Arithmetic exception.
         throw new ArithmeticException("Person is not eligible to vote");    
      }  
      else {  
         System.out.println("Person is eligible to vote.");  
      }  
  }  

  //main method  
  public static void main(String args[]){  
    //call method  
    check_age(13);   
  }    
}
Output
Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to vote
at TestThrow.check_age(TestThrow.java:6)

Example में आप देख सकते हैं की किस तरह से हमें error message मिला है। इसलिए throw keyword का use करके आप उस error को कोई भी explicit name दे सकते हैं। जहाँ भी need हो वहां किसी error को throw / generate भी कर सकते हैं।


ध्यान रहे exception throw करते समय दिया गया class का name Throwable या इसकी कोई sub class का name ही होना चाहिए। और अगर कोई user defined class use की है तो वह class Exception class को inherit करनी चाहिए।

Java throw user defined exception

File : ThrowTest.java

CopyFullscreenClose FullscreenRun
// inherit Exception class to throw custom error.
class MyException extends Exception  {  
    public MyException(String message)  {  
      // Calling parent constructor.
      super(message);  
    }  
}

class ThrowTest {    
  public static void main(String args[]){  
     try {  
        // now use MyException to throw exception
        throw new MyException("This is user defined exception");    
     }  
     catch(Exception error) {  
        System.out.println(error.getMessage());  
     } 
  }    
}
Output
This is user defined exception

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers