Runtime Stack

A runtime stack is a stack data structure that stores information about the active methods of a program. It is also known as Execution Stack, Control Stack, Invocation Stack and Call Stack. Each method call shows its presence on the stack using a Stack Frame. Stack frame is also known as an Activation Record. A stack frame consists of the information about its local variables. The method executing currently will be pushed at the top of stack. For example: if method A() calls B() and B() calls C(), then the call stack will be as shown below:
real java exception handling runtime stack
A method will stay on the stack until its completion. As it completes, will be removed from the stack.

The Stack Trace

The stack trace is an information about the active stack frames on runtime stack at a specific time during execution of the program. Stack trace is used to know about the point of failure that occurred during execution of a program. Java provides printStackTrace() and getStackTrace()methods to print all the stack trace elements on a runtime stack.
For Example:
class b
  {
  int getDivisionResult(int num,int denm)
	  {
		int dv=num/denm; /*Line No:5*/
		return (dv);
	  }
  void showDivisionResult(int num,int denm)
      {
        int res=getDivisionResult(num, denm);/*Line No:10*/
        System.out.println(“Result=”+res);
      }
  }
public class Stacktrace
  {
	public static void main(String[] args) 
	 {
	    b obj=new b();
	    System.out.println(“Started”);
	 try
	   { 
         obj.showDivisionResult(10, 0);/*Line No:22*/
	   }
	catch(ArithmeticException ex)
		{ 
          ex.printStackTrace();
		}
	System.out.println(“Completed”);
	 }
  }
Output:
        Started
        java.lang.ArithmeticException: / by zero
        at b.getDivisionResult(Stacktrace.java:5)
        at b.showDivisionResult(Stacktrace.java:10)
        at Stacktrace.main(Stacktrace.java:22)
        Completed

Using Keyword throw

You know that JVM creates object of Exception classes and throws its reference to the following catch block. It happens only when a specific run time error occurs.
However, you can instantiate Exception classes manually and can be thrown using keyword throw.
Throw keyword can be used with sub classes of java.lang.Throwable classes only. If you try throw with Integer class object:
   throw new Integer (“Error”);
The compiler refuses to compile and displays the following error message:
  incompatible types
  found: java.lang.String
  required: java.lang.Throwable
By using keyword throw, you can use available exception classes in more customized form. For example, in case of values of type double, division by zero does not throw ArithmeticException, it can be made possible by using keyword throw.
Implementation:
The following program demonstrates how to use the keyword throw with ArithmeticException class when divisor is zero. The program consists of two classes Process and ThrowClause. Class Process consists of a method doubleDivision(), which takes numerator(num) and denominator(dnm) as arguments; if denominator is zero then it creates an instance of ArithmeticException class and throws its reference to the catch block contained by main() method . Note that while instantiation some customized message is passed to show appropriate message on the screen.
 public class ThrowClause 
 { public static void main(String[] args) 
     {
	double n=10.8,d=0.0;
	System.out.println(“Start”);
         try{
	    double res=new Process().doubleDivision(n, d);
	    System.out.println(“double division result:”+res);
  	    }
         catch(ArithmeticException ex)
	  { System.out.println(ex.getLocalizedMessage());
	   }
	System.out.println(“Complete”);
       }
  }
class Process
   {
      double doubleDivision(double num,double dnm)
         {  if(dnm==0.0)
	     throw new ArithmeticException(“Do not Divide with Zero”);
	  else
	     return num/dnm;
	}
   }
 Output:
          Start
          Do not Divide with Zero
          Complete

Exception Types: Checked and Unchecked

In Java, there are basically two types of exceptions:
  • Checked Exceptions
  • Unchecked Exceptions
Java is one of the few languages that supports both checked and unchecked exceptions.
Checked Exceptions:
  • All exceptions, which are direct subclasses of java.lang.Exception except java.lang.RuntimeException, java.lang.Error and their subclasses are checked exceptions. For example: SQLException, IOException, EOFExceptions, FileNotFoundException etc belongs to checked category. In case of checked exceptions, a method can throw a checked exception directly or indirectly and the calling method must deal with it explicitly. The method which can throw checked exception must be called within try block or pass the exception using throws clause, otherwise it will be detected at compile time.
  • For Example:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    public class CheckedException 
    {
       static void inputOutput()
       {	
    	int i=0;   
    	String s=””;
    	InputStreamReader rdr=new InputStreamReader(System.in);
    	BufferedReader br = new BufferedReader(rdr);
    	System.out.print(“Enter String”);
    	s = br.readLine(); /*Line No. 13*/
    	System.out.print(“Enter Integer:”);
    	i=Integer.parseInt(br.readLine());
    	System.out.println(“Ur Result=”+s+”    “+ i);
       }
       public static void main(String args[]) throws IOException 
                { 
    	      inputOutput();
                }
        }
    
    Output
             (Compile Time Error)
             CheckedException.java:13:Unreported exception
             java.io.IOException; must be caught or declared to be thrown.
             s = br.readLine();
    
    Explanation: As shown in output, the compiler throws IOException because method readLine() throws IOException, which belongs to checked category. For successful compilation of this program, readLine() method should be invoked inside try block.

Unchecked Exceptions

All exceptions derived from classes: java.lang.RuntimeException and java.lang.Error, directly or indirectly are unchecked exceptions, for example, ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, IllegalArgumentException, AssertionError, AWTError and IOError etc belongs to unchecked exceptions category.
Unlike checked exceptions, you no need to keep your code inside try block to deal with them explicitly, for example, if you write:
		 int x = 5/0;  
the compiler will not show any error message, because division by zero (5/0) throws ArithmeticException, which belongs to unchecked ategory.

Using throws Clause

To understand throws, it is assumed that you have well understanding about checked exception. You know that, if a method throws a checked exception then the caller must handle it using try-catch block or should be passed to its caller.
Now question is how to pass it to calling method. The answer is “throws”. The throws clause is used in method header to specify the list of checked exceptions a method can throw.
Consider the following syntax:
returnType MethodName() throws ExceptionType1, ExceptionType2
{ ................................}
For Example:
 import java.io.*;
public class ThrowsDemo 
   {
	public static void main(String[] args){
        Input cin=new Input();
           try{
		String str=cin.getString();
		System.out.println(“String received:”+str);
	       }
	   catch(IOException ex)
		{ ex.printStackTrace(); }
	}//main() closed
   }
class Input
      {
      //using "throws"
	String getString() throws IOException 
	  {   	String s=””;
	    InputStreamReader rdr=new InputStreamReader(System.in);
	    BufferedReader br = new BufferedReader(rdr);
	    System.out.print(“Enter String :”);
	    s = br.readLine();  
	    return (s);
	  }	
      }
 Output
        Enter String :Real Java
        String received:Real Java
 
About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
17 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android. If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : [email protected] #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap