try-catch block

a try catch block prevents to crash the application to occur and intercept the Exceptions while runtime .

Syntax: 

try{

// code

catch([Exceptionclass ex]){

// error handling

}

But what is a Exception?Exception is an event , which collides  serious unforseen problem.Exception class is a subclass of Throwable.

 

Exception Hierarchy

A typical IndexOutofBoundExceptions occurs when you access the index of element which is higher than the size of an Array.Let’s surround our example with try catch block.

example:

try {
String[] text = new String[2];
System.out.println(text[3]);
}
catch (ArrayIndexOutOfBoundsException ex) {
ex.printStackTrace();
}

ex.printStackTrace() prints the Location of Exception handling.

It is possible to invoke exceptions with throw keyword.

Example:

public class Main {

	public static void main(String[] args)  {
        int ID = 2;
	if(ID == 2) {
		throw new ArithmeticException("Wrong ID");
	}
	}
}

The most common Mistakes that invoke Exceptions by beginners are:

  • NullPointerException – declare object without parameters
  • ArrayIndexOutofBoundException – placing wrong index on Array 
  • FileNotFoundException – Placing wrong path or it does not exist

Leave a Reply