Wednesday, 15 April 2020

SE - 47 - All about Exceptions !

Throwable 

-> Throwable is parent class(not interface) of all the exceptions and Errors.

-> We can use Throwable in catch block to catch all the exceptions :
     catch(Throwable t)

->The mostly used methods of Throwable class are :

public String getMessage()  - It returns a detailed message string of the Throwable instance (which may be NULL).

public StackTraceElement[] getStackTrace()  - An array of StackTraceElement as given by printStackTrace

Sample Code : 
   try{  
       int i=10/0;  
   }catch(Exception e){  
       StackTraceElement[] trace = e.getStackTrace();  
       System.err.println(trace[0].toString());  
       System.out.println(trace[0].getClass());  
       System.out.println(trace[0].getMethodName());  
       System.out.println(trace[0].getFileName());  
       System.out.println(trace[0].getLineNumber());  

}}

public Throwable getCause()  - It is used to fetch the cause of the Throwable or null if cause can't be determined. This function fetches the cause that was supplied by one of the constructors or that was set after creation with the initCause(Throwable) method. All the PrintStackTrace methods invoke getCause() method to determine the cause of the Throwable.


public void printStackTrace()  - The printStackTrace() method of Java Throwble class is used to print the Throwable along with other details like classname and line number where the exception occurred.


As I mentioned earlier throwable has its 2 kids : Error and Exception

An Error is some problem in the program which can't be handled by try catch block. The execution has to be stopped in case of error. Some common error examples are : 


  • InternalError
  • OutOfMemoryError
  • StackOverflowError
  • UnknownError
  • NoClassDefFoundError
  • UnsatisfiedLinkError
  • AbstractMethodError
  • IllegalAccessError
  • InstantiationError
  • NoSuchFieldError
  • NoSuchMethodError



Exceptions are reasonable and logical errors which can be handled by using try catch block. We can continue the execution . The methods of Exception class are inherited by Throwable. Some common exceptions in java are : 


  • InterruptedException
  • IOException
  • FileNotFoundException
  • ConnectException
  • UnknownHostException
  • ClassNotFoundException
  • IllegalAccessException
  • InstantiationException
  • NoSuchFieldException
  • NoSuchMethodException
  • RuntimeException
  • ArithmeticException
  • ArrayStoreException
  • ClassCastException
  • ConcurrentModificationException
  • IllegalArgumentException
  • IllegalThreadStateException
  • NumberFormatException
  • IllegalStateException
  • IndexOutOfBoundsException
  • ArrayIndexOutOfBoundsException
  • StringIndexOutOfBoundsException
  • NegativeArraySizeException
  • NullPointerException




No comments:

Post a Comment