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
- }
- }
- }
Unreachable Blocks:- The block of statements to which the control would never reach under any case can be called as unreachable blocks.
- Unreachable blocks are not supported by java.
- Thus catch block mentioned with the reference of "Exception" class should and must be always last catch block. Because Exception is super class of all exceptions.
Program:Ads by Roll AroundAd Options
- package com.instanceofjava;
- public class ExcpetionDemo {
- public static void main(String agrs[])
- {
- try
- {
- //statements
- }
- catch(Exception e)
- {
- System.out.println(e);
- }
- catch(ArithmeticException e)//unreachable block.. not supported by java. leads to error
- System.out.println(e);
- }
- }