Java Exceptions

Java – Introduction to Exceptions

Introduction: While Compiling and Executing Java application, chance of getting 3 types of errors. InputMismatchException: It occurs if user enter invalid input while reading through Scanner. import java.util.Scanner;class Code{            public static void main(String[] args) {                        Scanner sc = new Scanner(System.in);                        System.out.println(“Enter 2 numbers : “);                        int a = sc.nextInt();                        int b = sc.nextInt();                        int c …

Java – Introduction to Exceptions Read More »

Java – Finally Block

Finally block: class Code{      public static void main(String[] args)      {                  try                  {                              // int a = 10/5 ; -> try-finally blocks execute.                              // int a = 10/0 ; -> catch-finally blocks execute.                              System.out.println(“Try Block”);                  }                  catch (Exception e)                  {                              System.out.println(“Catch Block”);                  }                  finally                  {                              System.out.println(“Finally Block”);                  }      }} Why closing statements belongs to finally block? …

Java – Finally Block Read More »

Java – Custom Exceptions

Custom Exceptions: Defining Custom Exception: class MyException extends Exception{            // body;} throw: LowBalanceException obj = new LowBalanceException(“Low Balance in Account”);          throw obj; throws: String to int conversion: Pre-defined Method as follows: Method-1: we can handle using try-catch while using method. Method-2: throws the same exception without handling InvalidAgeException: import java.util.Scanner;class InvalidAgeException extends Exception{            InvalidAgeException(String name){                        …

Java – Custom Exceptions Read More »

Java – Try with Resources

try with resources: import java.io.*;class Code{            public static void main(String[] args) throws Exception            {                        try(FileInputStream file = new FileInputStream(“Code.java”))                        {                                    int ch;                                    while((ch=file.read()) != -1){                                                System.out.print((char)ch);                                    }                        }            }}

Scroll to Top