throw keyword:
- 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).
Program:
- package com.instanceofjava;
- public class MyExceptionThrow {
- public static void main(String a[]){
- try{
- MyExceptionThrow thr = new MyExceptionThrow();
- System.out.println("length of INDU is "+thr.getStringSize("INDU"));
- System.out.println("length of SAIDESH is "+thr.getStringSize("SAIDSH"));
- System.out.println("length of null string is "+thr.getStringSize(null));
- }
- catch (Exception ex){
- System.out.println("Exception message: "+ex.getMessage());
- }
- }
- public int getStringSize(String str) throws Exception{
- if(str == null){
- throw new Exception("String input is null");
- }
- return str.length();
- }
- }
Output
length of INDU is 4
length of SAIDESH is 5
Exception message: String input is null
throws keyword:
- The functionality of throws keyword is only to explicitly to mention that the method is proven transfer un handled exceptions to the calling place.
Program:
- package com.instanceofjava;
- public class ExcpetionDemo {
- public static void main(String agrs[]){
- try
- {
- //statements
- }
- catch(Exception e)
- {
- System.out.println(e);
- }
- finally(){compulsorily executable statements
- }
- }
- }