Monday, August 12, 2024

Exception Handling

Exception Handling:

FAQ : Hierarchy of Exceptions :

In Java, exception handling is organized in a class hierarchy.

The base class for all errors and exceptions is Throwable.

The hierarchy is structured as follows:

Throwable (class)

   /        \

  /          \

Error (class)   Exception (class)

Super class for all error and Exception  -  throwable class

Under throwable  class- we have 2 child classes

1. error

2 Exception

 

Throwable: This is the root class for all errors and exceptions in Java

It is the superclass of both Error and Exception

public class Throwable {

    // Common methods and properties

}

public class Error extends Throwable {

    // Represents errors that are not meant to be caught

}

public class Exception extends Throwable {

    // Represents exceptions that applications might want to catch

}

 

Error represents serious issues that usually cannot be handled

Exception represents conditions that applications might catch and handle.

 

Exception Handling:

Need of Exception handling :

 

package ExceptionHandlingBasics;

public class ExceptionBasics1 {

               public static void main(String[] args)

               {

                              System.out.println("stmt-1");

                              System.out.println("stmt-2");

                              int a = 10/0;//  cannot divide any no by zero = infinite

                              //

                             

                              System.out.println("stmt-3");

                              System.out.println("stmt-4");

               }

}

o/p:

stmt-1

stmt-2

Exception in thread "main" java.lang.ArithmeticException: / by zero

               at ExceptionHandlingBasics.ExceptionBasics1.main(ExceptionBasics1.java:9)

 

When a program encounters an error or exception, it typically stops execution at the line where the error occurs. This can prevent subsequent statements from being executed and interrupt the normal flow of the program.

Even though we have error/ Exception, we want to continue our program execution without interruption is called exception handling.

By using exception handling, you can:

  • Catch Errors: Detect and handle errors at specific points in the program without stopping the entire execution.
  • Continue Execution: Ensure that the program can continue running and execute subsequent statements or perform alternative actions, even if an error occurs in some part of the code.

 

 

Exception handling with "try catch" block:

1.ArithmeticException:

-occurs if any no is divisible by 0

 

package ExceptionHandlingBasics;

public class ArithmeticExceptionBasics1 {

               public static void main(String[] args) {

              

                              System.out.println("stmt-1");

                              System.out.println("stmt-2");

                              //  exception handling can be done by using  try catch block

                              // try ,  catch -   keywords in java

                              //   can be used to define block

                              //define  try block, catch block

                              try

                              {

                                             int a=10/0;//  cannot divide any no by zero

                              }

                              catch (ArithmeticException  ae)

                              {

                                             System.out.println("catching ArithmeticException.cannot divide no by zero  ae ="+ ae);

                              }

                             

                              System.out.println("stmt-3");

                              System.out.println("stmt-4");

               }

}

o/p:

stmt-1

stmt-2

Catching Exception cannot divide no by zero :java.lang.ArithmeticException: / by zero

stmt-3

stmt-4

2. ArrayIndexOutOfBoundsException:

ArrayIndexOutOfBoundsException  occurs when you attempt to access an array with an invalid index, meaning the index is either negative or greater than or equal to the size of the array.

 

package ExceptionHandlingBasics;

public class ArrayIndexOutofBoundsExcpetion21 {

               public static void main(String[] args) {

                              System.out.println("stmt-1");

                              System.out.println("stmt-2");

                             

               // Define int array {10,20,30};

                              int iarr []= {10,20,30};

                              //             0   1   2   invalid 3 index no

                             

                              // try to store 40 using indexno = 3

                              iarr[3]  = 40;

//                           Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

//                           at ExceptionHandlingBasics.ArrayIndexOutofBoundsExcpetion21.main(ArrayIndexOutofBoundsExcpetion21.java:14)

                             

                              System.out.println("stmt-3");

                              System.out.println("stmt-4");

               }

}

o/p:

stmt-1

stmt-2

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

               at ExcpetionBasics.ArrayIndexOutofBoundsExcpetion2.main(ArrayIndexOutofBoundsExcpetion2.java:12)

package ExceptionHandlingBasics;

public class ArrayIndexOutofBoundsExcpetion2 {

               public static void main(String[] args)

               {

                              System.out.println("stmt-1");

                              System.out.println("stmt-2");

                              int arr [] = {10,20,30};

                              //             0   1   2   invalid 3 index no

                              // handle exception using try-catch block

                              try

                              {

                                             arr[3] =40; //  stops program execution here, after that it does not execute next stmts

                                             //stmt-2

                                             //                                          Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

                                             //                                          at ExcpetionBasics.ArrayIndexOutofBoundsExcpetion2.main(ArrayIndexOutofBoundsExcpetion2.java:12)

                              }

                              catch (ArrayIndexOutOfBoundsException ae)

                              {

                                             System.out.println("Catching ArrayIndexOutOfBoundsException :ae:"+ae);

                              }

                                             System.out.println("stmt-3");

                              System.out.println("stmt-4");

               }

}

o/p:

stmt-1

stmt-2

Catching ArrayIndexOutOfBoundsException :e:java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

stmt-3

stmt-4

3. Stringindexoutofboundsexception :

occurs when string index no is out of boundary

 

package ExceptionHandlingBasics;

public class StringIndexOutOfBoundsExceptionBasics {

               public static void main(String[] args) {

                              System.out.println("stmt-1");

                              System.out.println("stmt-2");

                             

                              String s = "Ram";

                              //          012

                              // get char at index no =3

                              char ch = s.charAt(3);

                              // Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3

                              //                           at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)

                              //                           at java.base/java.lang.String.charAt(String.java:712)

                              //                           at ExcpetionBasics.ArrayIndexOutofBoundsExcpetion2.main(ArrayIndexOutofBoundsExcpetion2.java:11)

                              System.out.println("stmt-3");

                              System.out.println("stmt-4");

               }

}

o/p:

stmt-1

stmt-2

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3

               at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)

               at java.base/java.lang.String.charAt(String.java:712)

               at ExcpetionBasics.ArrayIndexOutofBoundsExcpetion2.main(ArrayIndexOutofBoundsExcpetion2.java:11)

StringIndexOutOfBoundsException with try Catch block:

package ExceptionHandlingBasics;

public class StringIndexOutOfBoundsException2 {

               public static void main(String[] args) {

                              System.out.println("stmt-1");

                              System.out.println("stmt-2");

                              String s = "Ram";

                              //          012

                              // handle exception using try -catch block

                              try {

                                             char ch = s.charAt(3);

                                             // Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3

                                             //                                          at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)

                                             //                                          at java.base/java.lang.String.charAt(String.java:712)

                                             //                                          at ExcpetionBasics.ArrayIndexOutofBoundsExcpetion2.main(ArrayIndexOutofBoundsExcpetion2.java:11)

                                             System.out.println("in try block");

                              }

                              catch (StringIndexOutOfBoundsException sie)

                              {

                                             System.out.println("catching StringIndexOutOfBoundsException. sie= "+sie);

                              }

                              System.out.println("stmt-3");

                              System.out.println("stmt-4");

               }

}

o/p:

stmt-1

stmt-2

catching StringIndexOutOfBoundsException. sie= java.lang.StringIndexOutOfBoundsException: String index out of range: 3

stmt-3

stmt-4

4. Nullpointer Exeption:

when object reference is null, if we call any methods using object reference variable

 String s =  "Ram";

               s.length();

  s = null;

   s.length();

  null. length()     --> nullpointer  Exception

---------------------

package ExceptionHandlingBasics;

public class NullPointerException3 {

               public static void main(String[] args) {

                              System.out.println("stmt-1");

                              System.out.println("stmt-2");

                              // define String s  = "Ram"

                              String s = "Ram";

                             

                              System.out.println("length of string s="+ s.length());

                              // store null value in s

                              s = null;

                              // now get lenth of string

                             

                             

                              System.out.println("length of string="+ s.length());

                              //                                     

                                             ////                           null. length() --> Null pointerEXception

                                            

                              System.out.println("stmt-3");

                              System.out.println("stmt-4");

               }

}

o/p:

stmt-1

stmt-2

length of string s=3

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "s" is null

               at ExceptionHandlingBasics.NullPointerException3.main(NullPointerException3.java:17)

Note:

If any object reference variable or object name  =  null, it does not refer object value.

If we try to call any method using object refer variable (null), it throws 'NullPointer Exception'

ex:

     s.length();

    null.length() -->  NullPointerException

    Emp1  eref1 = null;

     eref1.getSalary();

     

   //  null *  any Method ---> NullPointerException

HW  Handle above NullPointerException using try catch block :

Multiple Catch blocks:

In Java, you can handle multiple exceptions using multiple catch blocks. This approach allows you to specify different handling mechanisms for different types of exceptions.

 

// We can write single try and single catch block

                              //               single  try   and multiple catch blocks

  try

{

}

catch(Exception e)

{

}

syntax 2:  single try - multiple catch blocks

  try

{

}

catch(ArrayIndexOutOfBoundsException ae)

{

}

catch(ArithmeticException ae)

{

}

catch(StringIndexOutOfBoundsException sie)

{

}

catch(Exception e)

{ // // Handle any other Exception

}

This structure allows you to handle specific exceptions with dedicated catch blocks, and a more general catch block at the end to handle any other exceptions that might not have been specifically caught by the earlier blocks. The order of catch blocks matters, with more specific exceptions coming before the more general Exception class

 

 

package ExceptionHandlingBasics;

import OperatorsBasics.ArithematicOperators;

public class TestMultipleTryCatchBlocks {

               public static void main(String[] args) {

                              // Define single try - multiple catch blocks

                              try

                              {

//                                          int res =  10/0;                                

//                                          int arr [] = {10,20,30};

//                                          arr[3]  =35;// ArrayIndexOutOfBoundsException

                                            

//                                          String s = null;// NullPointerException

//                                          s.length();// 

                                            

                                             String s = "Ram";// 012 

                                             s.charAt(5);// StringIndexout                                    

                              }

                               

               // catch -ArithmeticException

                              catch (ArithmeticException ae) {

                                             System.out.println("Catching ArithmeticException");

                              }                            

              

               //catch -ArrayIndexOutOfBoundsException

                              catch(ArrayIndexOutOfBoundsException aie)

                              {

                              System.out.println("Catching ArrayIndexOutOfBoundsException.");

                              }

               //catch -NullPointerException

                              catch(NullPointerException ne)

                              {

                              System.out.println("Catching NullPointerException.ne =");

                              }

                              catch(StringIndexOutOfBoundsException sie)

                              {

                                             System.out.println("Catching StringIndexOutOfBoundsException =");

                              }

                             

                              System.out.println("program ends here ");

               }

}

                             

package ExceptionHandlingBasics;

public class TestMultipleTryCatchBlocks {

               public static void main(String[] args) {

                              // Define single try - multiple catch blocks

                              try

                              {                            

//                                                         int res =  10/0;

//                                                         int arr [] = {10,20,30};

//                                                         arr[3]  =35;// ArrayIndexoutof

                                                            String s = null;// NullPointerException

                                                            s.length();// 

                                            

                                             String s2 = "Ram";

                                             char ch  =s2.charAt(5);// StringIndexout

                              }

                              // catch -ArithmeticException

                              catch (ArithmeticException ae) {

                                             System.out.println("Catching ArithmeticException. ae ="+ ae);

                              }             

                              ////catch -ArrayIndexOutOfBoundsException

                              catch (ArrayIndexOutOfBoundsException ai)

                              {

                                             System.out.println("Catching ArrayIndexOutOfBoundsException.ai "+ai);

                              }

                              //catch -NullPointerException

                              catch (NullPointerException ne)

                              {

                                             System.out.println("Catching NullPointerException.ne="+ne);

                              }

                              // catch -Exception   will catch any type of exception

                              catch(Exception e)// this can be used at the end only

                              {

                                             System.out.println("Catching any type of exception.arre ="+e);

                              }

                              System.out.println("ends here");

               }

}

                              // catch -Exception   will catch any type of exception

                                                                          

                                             System.out.println("Catching any type of exception.arre ="+e);

              

                              System.out.println("ends here");

}

o/p:

Catching any type of exception.arre =java.lang.StringIndexOutOfBoundsException: String index out of range: 5

ends here

Based on Exception, it goes to respective catch block with given Exception,   executes catch block..

Exception and error:

Exception is run time event that occurs, while running the program only.

- Predefined class

               Throwable(C)

Error(C)               Exception(c)

                                             ArithmeticException(C)

                                             ArrayIndexOutOfBoundsException(C)

                                             NullPointerException(C)

                                             StringIndexOutOfBoundsException(C)

Error :

  Error occurs while writing program

ex:  syntax errors:

Examples of syntax errors include

·        missing ;  at the end  of statement , missing (.....etc in stmt.

·        duplicate local variables are not allowed

 

Find the errors:

package ExceptionHandlingBasics;

public class ErrorsBasics {

               public static void main(String[] args) {

                             

//                           String s = "Ram"     // error insert ;Syntax error, insert ";" to complete BlockStatements

                                                            // Each stmt must end with semicolon i.e ;

                                                            int a =10;

//                                                         int a =20; // Error: Duplicate local variable a

                                                             a  =30;

                                                              a =  a+2;

               }

}

FAQ Diff b/w Exception and error?

1. Exception: Occurs at runtime only when the program is executing.


Error: Generally occurs during the development or compilation phase.

2. Exception - can be handled by using try and catch - block

   Error - cannot be handled by using try catch block-  which must be fixed, while writing program only.

  If error is not fixed in program, we cannot Run any Java program.

Finally and Final:

·        "finally is a predefined keyword in the Java programming language

·        It is used in conjunction with a try-catch block  or it can be used to define with try -catch block.

·        The finally block always gets executed, whether an exception is thrown or not.

 or

Fiinally block always gets executed, if exception is there

Finally block always gets executed, even if exception is not there also

syntax:

finally

{

       stmt-1;

        stmt-2;

}

 

Ex1:

package ExceptionHandlingBasics;

public class FinallyBasics {

               public static void main(String[] args)

               {

                              try

                              {

//                                          int a= 10/0;// Aritematic exception

                                             int a =5/2;//

                              }

                              catch(Exception e)

                              {

                                             System.out.println("catching Excception ="+e);

                              }

                              // Define finally block

                              finally

                              {

                                              //  always gets excecuted if exception is there

                                  //                            even if exception is not there also        

                                             System.out.println("finally block always gets excecuted if exception is there or not ");

                              }

               }

}

o/p:

finally block always gets excecuted if exception is there or not

finally block always gets executed if exception occurs or even if exception does not occur.

 

We can write single try -finally

package ExceptionHandlingBasics;

public class FinallyBasics {

               public static void main(String[] args)

               {

                              // we can write try-finally block

                              //                           try-catch,  try -ctach-finally, try -finally

                              try

                              {

//                                          int a= 10/0;

                                                                                                                        int a =5/2;

                              }

                              //                           catch()

                              finally

                              {

                                             //  always gets executed if exception is there

                                             //                            even if exception is not there also        

                                             System.out.println("finally block always gets executed if exception is there or not ");

                              }

               }

}

Note:

1. single try - single-catch block

try

{

}

catch(Exception e)

{

}

2:  single try - multiple catch blocks

ex:

try

{

}

               // catch -ArithmeticException

                              catch (ArithmeticException ae) {

                                             System.out.println("Catching ArithmeticException");

                              }                            

              

               //catch -ArrayIndexOutOfBoundsException

                              catch(ArrayIndexOutOfBoundsException aie)

                              {

                              System.out.println("Catching ArrayIndexOutOfBoundsException.");

                              }

               //catch -NullPointerException

                              catch(NullPointerException ne)

                              {

                              System.out.println("Catching NullPointerException.ne =");

                              }

                              // catch -Exception   will catch any type of exception

                                                            catch(Exception e)// this can be used at the end only

                                                            {

                                                                           System.out.println("Catching any type of exception.arre ="+e);

                                                            }

                             

3. try- catch - finally

try

{

}

catch(ArithematicException ae)

{

}

finally

{

}

4. try- finally

try

{

}

finally

{

}

Can We write multiple finally block?

We cannot write multiple finally blocks. We have to write only one finally block.

try - either we have to write catch block or finally block.

ex:

               try

                              {

                                             int a=10/0;

                              }

                              catch(Exception e)

                              {

                                            

                              }

ex2:

               try

                              {

                                             int a=10/0;

                              }

                             

                              finally

                              {

                                            

                              }

-------------

package ExcpetionBasics;

public class FinallyBasics {

               public static void main(String[] args)

               {

                              // Define try - multiple catch block - finally

                             

                                             int a= 10/0;

//                                          int a =5/2;

                                            

                              catch(ArithmeticException ae)

                              {

                                             System.out.println("catching ArithmeticException ="+ae);

                              }

                              catch(Exception e)//

                              {

                                             System.out.println("catching Excception ="+e);

                              }

                                             //  finally block

                               //  always gets excecuted if exception is there

                                  //                            even if exception is not there also        

                                             System.out.println("finally block always gets excecuted if exception is there or not ");

                             

                             

                             

                              // Can we write multiple try-catch  blocks in the same class?  yes

                              try

                              {

                                            

                              }

                              catch (Exception e)

                               {

                             

                              }

                             

               }

}

Note:

final k/w is applicable for variable,  Method, class..

 

Define final variable -->  final  float pi = 3.14f;

Define final method -->  

                final      void M1()

                              {

                              }

Define final class -->  final class student

 

HW  Final:

package ExcpetionBasics;

public class finalVariable {

               public static void main(String[] args) {

                              // Define final variable  pi=3.14f;// final var

                              //  whose val is finalised / const, we cannot change final variable value

                              pi = pi +1;

                              // The final local variable pi cannot be assigned. It must be blank and not using a compound assignment

                              // if we try to change final variable value, it throws CE

                             

               }

}

Final Method:

FAQ : Can we override final method?

If we define final k/w before method name - it is final method.

If it is final method - we cannot change method body/ cannot override final method, it throws error i.e cannot override the final method from A

ex:

package ExceptionHandlingBasics;

public class A1

{

               // define final Method M1()

               final void M1()   // final method

                              {

                              System.out.println("Final method - cannot me modified");

                              }

                                            

}

package ExceptionHandlingBasics;

public class FinalMethods extends A1

{

               //extends A1

                              // Over riding  final methods M1()  is possible ?? No

                                              //CE:  Cannot override the final method from A1

//                                          void M1()// error

//                                          {

//                                          System.out.println("Final method -Test");

//                                          }

                             

                              public static void main(String[] args) {

                                             // create obj for FinalMethods- class

                                             FinalMethods fm = new FinalMethods();

                                             // call M1()

                                             fm.M1();

                              }

               }

o/p:

We cannot inherit final class.

ex:

package ExcpetionBasics;

// define final class -A

               //  final class

              

              

// check final class can be inherited or not

public class finalVariable

{  //  extends A //error

 // The type finalVariable cannot subclass the final class A

               // final class cannot be inherited.  so dont use final class as parent class

               public static void main(String[] args) {

                             

               }

}

-------------------------------

No

Throw:

·  throw is a predefined keyword in Java.

·  It is used to explicitly throw an exception in the code.

·  The exception can be any type, either predefined or user-defined.

                              int n = 10/0;// AE

syntax: 

throw new ExceptionType("Some message");

Examples:

//1. throw ArithmeticException

-->  throw new ArithmeticException("throwing  ArithmeticException");

//2 throw ArrayIndexOutOfBoundsException 

-->  throw new ArrayIndexOutOfBoundsException ("throwing  ArrayIndexOutOfBoundsException  ")

//3 .throw StringIndexOutOfBoundsException

--> throw new StringIndexOutOfBoundsException("throwing  StringIndexOutOfBoundsException");

                             

// HW throw NullPointerException  with args and without args

                             

// HW throw ArrayIndexOutOfBoundsException  with args and without args

                             

throw with try:

ex:

package ExceptionHandlingBasics;

public class throwBasics {

               public static void main(String[] args) {

                              try

                              {

                                             // throw ArithmeticException without writing 10/0

//                                          throw new ArithmeticException("throwing ArithmeticException in run time");

                                             // throw new StringIndexOutOfBoundsException

                                             throw new StringIndexOutOfBoundsException("throw StringIndexOutOfBoundsException");

                                             // error : Unreachable

                                             // HW   throw ArithmeticException

                                            

                                             // HW throw NullPointerException

                                            

                                             // HW throw ArrayIndexOutOfBoundsException                               

                              }

                              // catch -(StringIndexOutOfBoundsException 

                              catch(StringIndexOutOfBoundsException sie)

                              {

                                             System.out.println("Catching StringIndexOutOfBoundsException." );

                              }

                              //            catch-ArithmeticException

                              catch(ArithmeticException ae )

                              {

                                             System.out.println("Catching ArithmeticException.ae=");

                              }

               }

}

Throws:

·  throws is a predefined keyword in Java.

·  It can be used to throw away exception in method without handling it

·  The throws keyword is placed after the method name in the method signature.

·  Multiple exceptions can be declared using the throws keyword, separated by commas.

 (Or ) We can throw multiple exceptions without handling it.

                              //ex:   public static void main(String[] args) throws InterruptedException, FileNotFoundException

                                                           

                                             package ExceptionHandlingBasics;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

public class ThrowsBasics {

               public static void main(String[] args) throws FileNotFoundException, InterruptedException

               {

                              // reading Files

                              // create File - class obj 

                              File f  = new File("C:\\ testData.txt");

                              // create FileReader - obj

                              FileReader fr = new FileReader(f);

                              // Unhandled exception type FileNotFoundException

                             

                               Thread.sleep(4000);//   give data in ms --  =  4 sec

                               //Error: Unhandled exception type InterruptedException

                              // throws InterruptedException

                              // We can throw multiple exceptions without handling it

                              //ex:   public static void main(String[] args) throws InterruptedException, FileNotFoundException

                                                           

               }

}

FAQ: Difference Between throw and throws Keywords?

1. Throw can be used to throw an exception explicitly from a method or any block of code.

Ex:

throw new ArithmeticException("Division by zero");

2.  It can throw only one specific exception at a time during runtime.

3. The throw statement is used inside a method or block of code.

 

1.throws - we can throw away exception without handling in method.

  M1() throws FileNotFoundException

Ex: public void readFile() throws FileNotFoundException {

    // Code to read file

}

2. We can throw away multiple exceptions

public static void main(String[] args) throws InterruptedException, FileNotFoundException

{

}

3. The throws clause is used in the method signature after the method name and parameter list.

Aspect

throw

throws

1. Usage

Used to explicitly throw a single exception.

Used to declare exceptions that a method might throw.

2. Example

throw new ArithmeticException("any msg");

void M1() throws FileNotFoundException { ... }

3. Number of Exceptions

Can throw only one exception at runtime.

Can declare multiple exceptions that the method might throw.

4. Location

Can be used inside a method.

Can be used after the method name in the method signature.

 

Different Types of Exceptions:

1. Checked Exception (or Compile-Time Exception)

2. unchecked exception

 

1. Checked Exception (or Compile-Time Exception):

1. Definition: Exceptions that are found and must be handled at compile time.

2. Who Identifies: The compiler identifies checked exceptions during the compilation process.

3. Examples:

  • FileNotFoundException
  • InterruptedException

 

package ExcpetionBasics;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

public class checkedExceptionsBasics {

               public static void main(String[] args)  {

                              // Files                

                              File f  = new File("C:\\test.txt");

//                           FileReader fr =  new FileReader(f);

                              // Unhandled exception type FileNotFoundException  -->  checked Exception

              

                             

                              Thread.sleep(4000); // it throws interruptedException

                              // checked exception

                             

//                           HW Write some more examples of  checked exceptions?

               }

}

2. Unchecked Exception (or Runtime Exception):

·  Definition: Exceptions that occur during the execution of the program (runtime) and are not checked at compile time.

 Or

While running program, if we get any exception -unchecked Exception

 

·  Who Identifies: The JVM (Java Virtual Machine) identifies unchecked exceptions at runtime.

·  Examples:

 

ArithematicExcpetion (C)

StringIndexoutofboundsException (C)

ArrayIndexOutofBoundsException(C)

NullpointerException(c)

HW  Write some more Unechecked Exceptions or RunTime Exceptions?

FAQ Diff b/w Checked Exceptions and Unchecked Exceptions?

HW Add  more Exceptions and when it occurs ?

HW     NumberFormatException ?

              

Exception Propogation:

Exception which is spreading/propagating/passed  from one method to other method is called Exception Propogation.

                              // ie. InterruptedException propogated from M1() to main()

For example, if an exception occurs in method M1() and is not handled there, it can be propagated to the calling method (e.g., main()), where it can be handled or further propagated.

Example: In the following code, an InterruptedException is propagated from the M1() method to the main() method.

 

package ExceptionHandlingBasics;

public class ExceptionPrpogation1

{

               // Define M1  with thread.sleep

               public static void M1() throws InterruptedException

               {

                                             Thread.sleep(3000);//  throws InterruptedException

               }

                             

                              public static void main(String[] args) throws InterruptedException

               {

                                             // create obj for ExceptionPrpoagtion1

                                             ExceptionPrpogation1 eref =  new ExceptionPrpogation1();

                                            

                                             // call M1()

                                             eref.M1();// Unhandled exception type InterruptedException

                                             // ie. InterruptedException propogated from M1() to main()

                              }

               }

User defined exception /Custom Exception:

HCL FAQ: How can you create a user-defined exception in Java?

If the exception is defined by programmer then is called User defined exception

Or

Definition: A user-defined exception is an exception that is created by the programmer to handle specific application logic that standard exceptions do not cover.

Example Scenarios:

1.      ATM Withdrawal Scenario:

    • Situation: You have a balance of $400 in your account, but you try to withdraw $500. The system should throw a custom exception indicating insufficient funds.
    • Custom Exception: NotHavingEnoughFundsException("Insufficient funds in your account")

 

ATM -->  400 balance

      Withdrawl some money 500 -->  not --front end - it displays error / Exception

                     Insufficient funds in ur account

throw my own exception -->  NotHavingEnoughFundsException("insufficient funds in ur account");

2.      Voting Eligibility Scenario:

  • Situation: To be eligible to vote, a person must be 18 years or older. If someone under 18 tries to vote, a custom exception should be thrown.
  • Custom Exception: InvalidAgeException("You are not eligible for voting as your age is below 18")

Steps to Create a Custom Exception:

·  Create a Class for the Custom Exception:

  • Define a new class with an appropriate name for the exception.
  • Extend the Exception class to inherit standard exception behavior.

·  Create a Constructor:

  • Inside the custom exception class, create a constructor that takes a String message as a parameter.
  • Call the super() method inside the constructor to pass the message to the parent Exception class.

package ExceptionHandlingBasics;

public class NotHavingEnoughFundsException extends Exception

{

//  steps  1. create constr and  pass String msg  2.  super() inside constr

              

               NotHavingEnoughFundsException(String msg)

               {

                              super(msg);

               }

}

package ExceptionHandlingBasics;

public class UserDefinedExceptionBasics

{

               public static void main(String[] args) 

               {

                              System.out.println("starts ");

                              // Define totalamt = 400;

                              int totalamt = 400;

                             

                              //Define cashwithdrawlamt = 500;

                              int cashwithdrawlamt = 500;

                              // Write if condition if cashwithdrawlamt >TotalAmt

                              // //   throw our own exception and catch

                              if(cashwithdrawlamt > totalamt )

                              {

                                             // throw -NotHavingEnoughFundsException

//                                          throw new ArithmeticException("We cannot divide any no by 0");

                                             try

                                             {

                                                            throw new NotHavingEnoughFundsException("throwing away my own exception--> NotHavingEnoughFundsException");

                                             }

                                             catch(NotHavingEnoughFundsException e)

                                             {

                                                            System.out.println("you dont have sufficient funds in ur account.Plz enter valid amount");

                                                            System.out.println("Exception details e="+ e);

                                             }

                              }             

                              else

                              {

                                             System.out.println("You have sufficient funds in your account");

                              }

                             

               }

}

o/p:

starts

you dont have sufficient funds in ur account.Plz enter valid amount

Exception details e=ExceptionHandlingBasics.NotHavingEnoughFundsException: throwing away my own exception--> NotHavingEnoughFundsException

create InvalidAgeException  class:

package ExceptionHandlingBasics;

public class InvalidAgeException extends Exception

{

//  1.must extend Exception

               //2 . constr

               //3 super

               InvalidAgeException(String msg)

               {

                              super(msg);

               }

}

package ExceptionHandlingBasics;

public class TestInvalidAgeException {

               public static void main(String[] args) {

               //  check InvalidAgeException is working fine

                                             int age =10 ;

                                             // check if age >=18 --> display msg "Eligible for voting"

//                                                                                       else throw InvalidAgeException

                                             if(age >=18)

                                             {

                                                            System.out.println("He/She is   eligible for voting");

                                             }

                                             else

                                             {

                                                            try

                                                            {

                                                                           throw new InvalidAgeException("throwing away My own Exception: InvalidAgeException");

                                                            }

                                                            catch(InvalidAgeException e)

                                                            {

                                                                           System.out.println("He/She is not  eligible for voting as Age must be >=18 for voting.Plz check ur age.");

                                                                           System.out.println("Exception details. e="+e);

                                                            }

                                             }

//                                                                                                     

               }

}

o/p:

He/She is not  eligible for voting as Age must be >=18 for voting.Plz check ur age.

Exception details. e=ExceptionHandlingBasics.InvalidAgeException: throwing away My own Exception: InvalidAgeException

HW  Create ur own Exception- CannotWithDrawlMoreThan50KException

, we cannot withdrawl more than 50,000 per day

Scenario: You cannot withdraw more than $50,000 in a single day.

HW  create ur own Exception --- InvalidPasswordException

  Check if the given password is "mercury". If it is correct, display "Password is correct". Otherwise, display "Password is not correct" and throw an exception.

Custom Exception: InvalidPasswordException

Can we write any statement in b/w  try and catch , try - finally?

package ExceptionHandlingBasics;

public class testTryCatch {

               public static void main(String[] args) {

                             

                              try

                              {

                                             int a=10/0;//  cannot divide any no by zero                                       

                              }             

                             

                              /// System.out.println("I am in b/w Try and catch -block"); // CE Dont write any stmt in b/w try and catch block

                             

                              catch(ArithmeticException ae)

                              {

                                             System.out.println("Catching ArithmeticException ="+ ae);

                              }

              

                             

                              System.out.println("stmt-3");

                              System.out.println("stmt-4");

               }

}

ex:

package ExceptionHandlingBasics;

public class testTryCatch {

               public static void main(String[] args) {

                             

                              try

                              {

                                             int a=10/0;//  cannot divide any no by zero                                       

                              }

// System.out.println("I am in b/w Try and catch -block"); // CE Dont write any stmt in b/w try and catch block

                             

                              catch(ArithmeticException ae)

                              {

                                             System.out.println("Catching ArithmeticException ="+ ae);

                              }

//                           System.out.println("I am in b/w catch - finally");// CE:   Dont write any stmt in b/w  catch block  and finally

              

                              finally

                              {

                                             System.out.println("it always gets executed if exception is there or even if exception is not there");

                              }

              

               }

}

              

Can we write nested try ?

package ExceptionHandlingBasics;

public class NestedTry {

               public static void main(String[] args) {

                              // define try block

                             

                              try  // outer try block

                              {

                                             System.out.println("in Try block");

                                            

                                             // Define inner try block

                                             try

                                             {

                                                            System.out.println("inner try block");

                                                            String s = null;

                                                            int l= s.length();// NPE

                                             }             

                                             catch(NullPointerException ne)

                                             {

                                                            System.out.println("Catching inner  exception ");

                                             }                                           

                                            

                              }

              

                              catch(Exception e)

                              {

                                             System.out.println("Catching outer  exception ");

                              }

              

              

                             

               }

}

Can we write try catch- try catch blocks?

package ExceptionHanldingBasics;

public class NestedTry {

               public static void main(String[] args) {

                             

                              try // inner try block

                              {

                                             System.out.println("1.try block");

                                             int a  =10/0;

                              }

                              catch (Exception e) {

                                             System.out.println("Catching 1st  exception ");

                              }

                             

                              System.out.println("Test-1");

                             

                              try {  // outer try block

                                                            System.out.println("2. Try block");                                                        

                                                            String s = null;

                                                                           int l= s.length();// NPE                                                

                              }

                              catch (Exception e)

                              {

                                             System.out.println("Catching 2nd  exception ");

                              }

                              System.out.println("Ends ");

               }

}

o/p:

1.try block

Catching 1st  exception

Test-1

2. Try block

Catching 2nd  exception

Ends

No comments:

Post a Comment

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...