samedi 22 décembre 2018

How to bypass any exception in java and have a working application.

How to bypass any exception in java

What is an Exception : 


Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.). In Java, an exception is an object that wraps an error event that occurred within a method and contains: Information about the error including its type.


How to catch an exception in Java

You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.

So in programing in java you use a try catch block and there you'll catch your exception and handle it

For example we want to catch a genral Exception without specification to allow your program to continue working without any bugs you need toput the specific code in a block

try{

//write treatement here 

}catch(Exception e){
//catch your exception
//handle it here 
}

With using this blocks you can catch any exception from crashing your application

The best practice is to call specific Exception classes such as IOException,NullPointerException not and not the Mother class.

So lets say you have two independent treatment to execute 
and you put then in a same try catch block and you want to execute the second treatement whatever happen with the first one
The try catch block only will not allow you to excute the second treatement if you got an exception in the first one so for that reason they added another block named finaly

The whole point of this finaly when an exception is catched and you want to execute a treatement for always whatever the exception catched or not you need to put it in the finaly block 

try{

//write treatement here 

}catch(Exception e){
//catch your exception
//handle it here
}
finaly{
// this treament will be always executed
}

you need to be sure to write a treament that will not crash your application else don't use this 
block

























Aucun commentaire:

Enregistrer un commentaire