Throw:
- throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
- If we are having our own validations in our code we can use this throw keyword.
- For Ex: BookNotFoundException, InvalidAgeException (user defined)
- //Custom exception
- package com.instanceofjavaforus;
- public class InvalidAgeException extends Exception {
- InvaidAgeException(String msg){
- super(msg);
- }
- }
- package com.instanceofjavaforus;
- 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);
- }
- }
- package com.instanceofjavaforus;
- public class ThrowDemo {
- public void method(){
- try{
- throw new NullPointerException("Invalid age for voting");
- }
- }catch(Exception e){
- System.out.println(e);
- }
- }
- public static void main(String agrs[]){
- ThrowDemo obj= new ThrowDemo();
- obj.method();
- }
- }
Throws:
- The functionality of throws keyword is only to explicitly to mention that the method is proven transfer un handled exceptions to the calling place.
- package com.instanceofjavaforus;
- public class ThrowSDemo {
- public void method(int a,int b) Throws ArithmeticException{
- inc c= a/b;
- }
- public static void main(String agrs[]){
- ThrowDemo obj= new ThrowDemo();
- try{
- obj.method(1,0);
- }catch(Exception e){
- System.out.println(e);
- }
- }
- }
Uses of throws keyword:
- Using throws keyword we can explicitly provide the information about unhand-led exceptions of the method to the end user, Java compiler, JVM.
- Using throws keyword we can avoid try-catch with respect to the statements which are proven to generate checked exceptions.
- It us highly recommended not to avoid try-catch with respect to the statements which are proven to generate exceptions in main method using throws keyword to the main() method.
No comments