Header Ads Widget

Responsive Advertisement

Exception understanding

Exception

An exception refers to any unforeseen or undesired event that disrupts the standard operation of a program. The primary purpose of an exception is to ensure the program can terminate gracefully. Exception handling provides an alternative approach to continue executing the remainder of the program despite the occurrence of an exception.

 

Runtime Stack mechanism?

 The runtime stack mechanism involves the Java Virtual Machine (JVM) creating a runtime stack for each thread. Every method call made is recorded in the respective stack. Each entry in this stack is known as a stack frame or activation record. Once a method call is completed, its corresponding entry is removed from the stack. After all method calls are finished, the JVM will clear the empty stack.

 

Default Exception Handling

When an exception occurs within a method, it is the responsibility of that method to create an exception object that includes the following information: a) the name of the exception, b) a description of the exception, and c) the location where the exception occurred (stack trace). After the exception object is created, the method passes it to the Java Virtual Machine (JVM). The JVM then checks if the method contains any exception handling code. If no such code is present, the JVM will terminate the method abnormally and remove the corresponding stack frame. Subsequently, the JVM identifies the calling method and checks for exception handling there as well. If no handling is found, the process continues.

 

Distinction Between Exception and Error

1. Exceptions are typically caused by issues within the program and are generally recoverable.

2. Errors, on the other hand, are usually not caused by the program itself and arise from a lack of system resources. Errors are considered non-recoverable.

Checked Exception vs. Unchecked Exception:

Checked exceptions are those that the compiler verifies during the program's compilation to ensure smooth execution at runtime. These exceptions are typically considered checked exceptions by default. An example of a checked exception is FileNotFoundException.

public class Test{

  public static void main(String …args){

            PrintWriter p=new PrintWriter(“abc.txt”);

            p.print(“Hello”);

     }

}

 

 

In this case, an exception may occur. Unchecked Exception: On the other hand, unchecked exceptions are not verified by the compiler, regardless of whether the programmer has implemented handling for them. Examples of unchecked exceptions include ArithmeticException and BombBlastException.

public class Test{

  public static void main(String …args) throws ClassNotFoundException{

            PrintWriter p=new PrintWriter(“abc.txt”);

            p.print(“Hello”);

     }

}

 

 

N.B

 It is important to note that both checked and unchecked exceptions occur at runtime; they do not arise during compilation. Additionally, RuntimeException and its subclasses, as well as Error and its subclasses, are categorized as unchecked exceptions.

 

Fully Checked vs Partially

Checked A checked exception is considered fully checked when all of its subclasses are also checked, such as IOException and InterruptedException. Conversely, a checked exception is deemed partially checked if only some of its subclasses are unchecked, like Exception and Throwable.

It is important to note that the only possible partially checked exceptions are 1) Exception and 2) Throwable.

 

How many ways are there to print an exception?

There are three methods:

a) e.printStackTrace();

b) System.out.println(e) or System.out.println(e.toString());

c) System.out.println(e.getMessage());

The Throwable class defines the following methods for printing exception information.

Method printable format

Method

printable

printStackStrace()  

name of exception :  description at stack trace

toString()

name of exception :  description

getMessage()

description

 

Example:

Public class Test{

 

Public static void main(String …args){

  Try{

   Sop(10/0);

 }catch(ArithemeaticException e){

   e.printStackTrace();

   Syso(e); or   syso(e.toString());

   Syso(e.getMessage());

}

}

}

 

Out put:

 

Java.lang.ArithmeticException : / by zero

        at  Test main();

 

Java.lang.ArithmeticException : / by zero

 

 / by zero

 

 

 

Final:

 

Final is the modifier applicable for classes, method and variables. If a class declared as final then we can’t extend that the class. i.e we can’t create child class for that class i.e inheritance is not possible for final classes.

If a method is final then we can’t override that method in child class

If a variable declared then we can’t perform reassignment that variable

 

Finally

Finally, is block always associated with try catch to maintain clean up code

Try{

Risky code

}catch(Exception e){

Exception handling code

}

Finally {

Clean up code

}

 

 

The specialty of finally block is it will be executed always respective of weather exception raise or not rise or handled or not handled this about finally block

 

Finalized

 

Finalized is a method always invoked by gc just before destroying object to perform cleanup activities Once finalized method complete immediately gc destroy that object

 

N.B Finally block is responsible to perform clean up related to try block i.e whatever resource we open at the part of try block will be inside finally block

Whereas finalized method is responsible to perform clean-up activities related to object i.e whatever resource associated with object will be dislocated before destroying an object by using finalized object

 

Various possible of Try catch of finally

In try, catch, finally order is important

Whenever we are writing try compulsory we should right catch or finally otherwise we will get compile time get error i.e try without catch or finally is invalid

Whenever righting catch compulsory try block must be required i.e catch without try is invalid

Whenever we writing finally compulsory, we should write try block i.e finally without try is invalid

Inside try catch finally we can decelerate i.e that is nesting of try catch finally is allowed

For try catch and finally block curly braces  are mandatory

Throw

Throw statement throw key word

 

kartik (programmer)   throw exception-----------> JVM  is catch this exception

 

Simple Example

Class Test{

Public static void main(String ..args){

 Syso(10/0);

}

}

 

 

If anyone not handle that time which method generate the exception, he is the responsible to call the JVM with location description for handover all of the information. After JVM will do the postmortem. And give console print. So by default e.printStackTrace() is there in throwable class.

 

Output:

Exception in thread “main”  java.lang.ArithmethicException :  /  by  zero

                             at Test.main(Test.java :4)

How throw key word used?

Some time we can create exception object explicitly and we can handover in manually for this we have to used throw key word

throw new ArithmethicExcption(“/ by zero”);

 Where throw keyword is handover our manual creation object to JVM

 

Hance the flowing two program is same

 

Public class Test{

Public static void main(String ..args){

   Syso(10/0);

}}

 

Output

Exception in thread “main”  java.lang.ArithmethicException :  /  by  zero

                             at Test.main(Test.java :4)

 

 

 

N.B in this case  main method is responsible to create exception object and handover to the JVM

Public class Test{

Public static void main(String ..args){

   throw  new ArithematicException(“/ by zero for explicitly”);

}}

 

Out put

Exception in thread “main”  java.lang.ArithmethicException :  /  by  zero for explicitly

                             at Test.main(Test.java :4)

 

N.B in this case programmer is responsible to create Exception object explicitly and handover to JVM manually.

 

 

Best use of throw key word is user define exception or customized exception

a>

 

Public class Test{

Public static void main(String ..args){

   Syso(10/0);

Syso(“Hello”);

}}

 

Output

Exception in thread “main”  java.lang.ArithmethicException :  /  by  zero

Public class Test{

Public static void main(String ..args){

throw new ArithmeticException(“/ by zero”); 

 Syso(“Hello”);

 

}}

 

Output

Test.java line 3 : unreacheable ,….

After throw statement we are not allowed to any statement directly other wise we get compile time error saying Unreachable statement

 

b>

Public class Test{

Public static void main(String ..args){

 throw new Test();

}}

 

Output

Get compile time exception

Incompatibility type

Found: Test

Required :java.lang.throwable

 

Public class Test extend RunTimeException{

Public static void main(String ..args){

 throw new Test();

}}

 

 

Output

Getting run time exception

Exception in thread “main”  Test

          at Test.main(Test.java:3)

After throw statement we are not allowed to any statement directly otherwise we get

We can use throw key word only for throw able type if we using normal java object, we will get compile time error saying in compatible type.

 

Throws keyword:

In our program if there is a possibility of rising checked exception then compulsory, we should handle the checked exception otherwise we get the compile time error saying

Unreported exception XXX must be caught or declared to be thrown

Import Java.io.*;

Public class Test{

Public static void main(String ..args){

 Printwriter pw=new PrintWriter(“abc.txt”);

Pw.print(“Hello”);

}

}

Out put

Compile time

Test.java:4 : Unreported exception java.io.FileNotFoundException must be caught or declared to be thrown

Printwriter pw=new PrintWriter(“abc.txt”);

                         ^

Error.

 

 

 

Example 2

Public class Test{

Public static void main(String ..args){

 Thread.sleep(1000);

}

}

Out put

Compile time

Test.java:3 : Unreported exception java.lang.InteruptedException must be caught or declared to be thrown

Thread.sleep(1000);

         ^

Error.

 

Example using Try catch

Public class Test{

Public static void main(String ..args){

Try{

 Thread.sleep(1000);

}catch(InteruptttedException e ){

}

}

}

 

 

 

Example using throws key word

 

a>Throws key word to delegate the responsible of error handling to caller(it may be another method or JVM) then caller method is responsible to handle that exception.

Public class Test {

Public static void main(String..args) throws  InterruptedException {

 Thread.sleep(1000);

}

}

 

b>Throws key required only for checked exception and use of throws key words unchecked exception there is no use or no impact

c>Throws keyword use only for convince to compiler. Use of throws key doesn’t prevent abnormal termination of the program.

 

Example

Public class Test {

Public static void main(String..args) throws  InterruptedException {

doStuff();

}

Public static void doStuff() throws  InterruptedException{

doMoreStuff();

}

Public static void doMoreStuff() throws  InterruptedException{

 Thread.sleep(1000);

}

}

 

N.B It is recommended to use try catch over throws key word

 

Case 1>

We can use throws key word in method and constructor not for classes

Public class Test throws Exception {// this is wrong in class

Public Test() throws Exception {   //this correct in constructor

}

Public void m1()throws Exception{//this correct in method

}

}

 

 

 

Case 2

We can use throws key word only for throw able type if we are trying to use for normal java class the we get compile time error saying incompatibility type error

 

 But class test extend RunTimeException

Public class Test{

Public static void main(String ..args){

 throw new Test();

}}

 

Output

Get compile time exception

Incompatibility type

Found: Test

Required :java.lang.throwable

 

Public class Test extend RunTimeException{

Public static void main(String ..args){

 throw new Test();

}}

 

 

Output

Getting run time exception

Exception in thread “main”  Test

          at Test.main(Test.java:3)

 

 

 

Case 3>

Public class Test{

Public static void main(String ..args){

 throw new Exception();

}}

 

Because Exception is checked exception

Output

Get compile time exception

Test.java:3 : Unreported exception java.io.Exception must be caught or declared to be thrown

throw new Exception();

           ^

Error.

Public class Test {

Public static void main(String ..args){

 throw new Error();

}}

 

Because Error is unchecked exception

Output

Getting run time exception

Exception in thread “main”  java.lang.Error

          at Test.main(Test.java:3)

 

Case 4>

With in the try block if there no chance of rising an exception then we can’t write catch block for that exception otherwise we will get compile time error saying Exception XXX is never thrown in body of corresponding try statement but this rule is applicable for fully check exception.

 

Example:

Public class Test{

Public static void main(String ..args){

Syso(“Hello”);

}catch(ArithmeticException e){

}}

 

 

 

 

Output:

Hello

Public class Test{

Public static void main(String ..args){

Syso(“Hello”);

}catch(Exception e){

}}

 

Output

Hello

Public class Test{

Public static void main(String ..args){

Syso(“Hello”);

}catch(IOException e){

}}

 

Output

Test.Java: 9 java.lang.IOException is never thrown in body of corresponding try statement

catch(IOException e)

^

Error

 

but this rule is applicable for fully check exception

Public class Test{

Public static void main(String ..args){

Syso(“Hello”);

}catch(InturreptedException e){

}}

 

 

 

 

 

Output:

 

Test.Java: 9 java.lang.IOException is never thrown in body of corresponding try statement

catch(InturreptedException e)

^

Error

 

 but this rule is applicable for fully check exception

Public class Test{

Public static void main(String ..args){

Syso(“Hello”);

}catch(Error e){

}}

 

Output

Hello

 

 

throw

thorws

To handover our created Exception object to JVM manually

Throws key word to delegate the responsible of error handling to caller(it may be another method or JVM) then caller method is responsible to handle that exception

 

Remind:

a>try:  to maintain the risky code

b>catch: to maintain exception handling code

c>finally: to maintain clean up code

d>throw: to handover our created Exception object to JVM manually

e>throws: to delegate the responsible of exception handling to caller

f>thrown: no such key word in java

 

Various possible Compile time errors in Exception Handling

1>When checked exception are not handling then we will get like

 Test.java:3 : Unreported exception java.io.Exception must be caught or declared to be thrown

throw new Exception();

           ^

Error.

 

 

 

2>When we use multiple catch block and first use Exception after then use ArithemeticException  then you got below exception?

Test.java:3 : java.lang.ArithematicException already been caught

 

 

3> Test.Java: 9 java.lang.IOException is never thrown in body of corresponding try statement

catch(IOException e)

^

Error

 

4> when we used after throw any other statement then we get : unreachable Statement

 

5> Incompatibility type

Found: Test

Required :java.lang.throwable

 

 

6>try without catch or finally

7>catch with out try

8>finally without try

 

Customized:

 

Some times to meet to programming requirement we can define our own exception is called customized or user define exception

 

It is highly recommended to define customized exception as unchecked i.e we have to extended RunTimeException but not exception

 

How you will do the Checked Exception to unchecked Exception?

Example

class BelowAgeException extends RuntimeException

{

BelowAgeException(String s){

 super(s);

}

}

 

 

class OldAgeException extends RuntimeException

{

OldAgeException(String s){

 super(s);

}

}

 

class CustException{

 

public static void main(String .. args){

int age=Integer.parseInt(args[0]);

if(age >60){

throw new OldAgeException(“your age is to old for govt jobs ”);

}else if(age<18){

throw new BelowAgeException (“your age is not eligible for govt jobs ”);

}else{

System.out.println(“You will get shortly in your mail”);

}

}}

 

How you will do the UnChecked Exception to Checked Exception?

 

class BelowAgeException extends Exception

{

BelowAgeException(String s){

 super(s);

}

}

 

 

class OldAgeException extends Exception

{

OldAgeException(String s){

 super(s);

}

}

 

class CustException{

 

public static void main(String .. args) throws Exception{

int age=Integer.parseInt(args[0]);

if(age >60){

throw new OldAgeException(“your age is to old for govt jobs ”);

}else if(age<18){

throw new BelowAgeException (“your age is not eligible for govt jobs ”);

}else{

System.out.println(“You will get shortly in your mail”);

}

}}

 

 

N.B throw keyword is best suitable for Customized Exception or User defined Exception but not for Predefine exceptions.

 

 

Top 10 exception?

Based on the person who is the rising the exception all exception is divided into 2 categories

 

  1. JVM exception
    •  
  2. Programmatically exception
    • Programmer
    • API developer

IllegalSateException it is the child class of RuntimeException and also unchecked exception raised by programmer to indicate that a has been invoked at run time after starting we are not second starting otherwise we get IllegalSateException

Thread t =new thread();

t.start(); //valid

t.start(); // IllegalSateException

 

AssertionError

It is the child class of error hence this unchecked raised that explicitly by the programmer or API developer to indicate the assert statement fails.

AssertionError()

 

 

Exceptio/Error

Raised By

  1. ArrayIndexOutOfBoundException
  2. NullPointerException
  3. ClassCastException
  4. StackOverFlowError
  5. NoClassDefFoundException
  6. ExceptionInitializerError
  7. IllegalArgumentException
  8. NumberFormatException
  9. IllegalStateException
  10. AsseritionError

1-6 Raised by JVM   and 7-10 raised by Programmer or API developer

 

 Try with multiple resources

 

We can declare multiple resource using semicolon

Like

try(r1;r2;r3){

}catch(){

}

 

Example

try(FileWrite fw=new FileWrite(“Output.txt”); FileReader fr=new FileReader(“input.txt”)){

 

}catch(){

}

 

 

All resource reference variables are implicitly final hence with in try block we can’t perform reassignment otherwise we will get compile error

Example:

1>

try(FileWrite fw=new FileWrite(“Output.txt”)){

fw=new FileWrite(“Output1.txt”))//get excption

}catch(){

}

Uto_closeable resource may not be assignment

2>

try(FileWrite fw=new FileWrite(“Output.txt”)){

//fw=new FileWrite(“Output1.txt”))//get excption

}catch(){

}

 

 

Until 1.6 version try should be associated with either catch or finally but from 1.7 version own words we can take only try with resource without finally or catch

 

The main advantage is of try with resource is we are not required finally block explicitly because we are not required to closed hence until 1.6 version finally block is hero but 1.7 onwards it is dummy and become or zero.

 

Multi catch block

Jdk1.6

Jdk 1.7

try{

}catch(AE e){

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}catch(NPE e){

Syso(e.getMessage());

}catch(InturreptedException e){

e.getMessage();

}

}

try{

}catch(AE | IOException e){

e.printStackTrace();

} catch(NPE | InturreptedException e){

Syso(e.getMessage());

}

}

 

In multi catch block there should not be any relation between exception types (Either Child to parent or Parent to child or same type otherwise we will get compiler time error)

 

Example    A

try{

int i=10/0;

String s=null;

Sop(s.length());

}catch(AE | NPE | Exception e){

Sop(e.getMessage());

}

 

Get compile time Exception:

Alternatives in multi-catch statement can not be related by subclass

                                    catch(AE | NPE | Exception e)

                                                                 ^

Error.

 

Example B

try{

int i=10/0;

String s=null;

Sop(s.length());

}catch(AE | NPE  e){

Sop(e.getMessage());

}

 

 

This is giving run time error.

 

 

Exception propagation?

Inside a method if a exception raised that and if we are not handling that exception then exception object will be propagated to caller then caller method is responsible the handle exception. This process is called exception propagation.

 

How you will covert one exception to another exception (re-throwing exception)?

try{

int i=20/0;

}catch(AE e){

throw new NullPointerException();

 }

 

 

Exception understanding
Exception understanding

Post a Comment

0 Comments