Exceptional Example in Java using throw 

Using the Throw

The throw an exception can be explicitly used by using the keyword throw statement. For example you have entered wrong username and password in login form need to thrown an exception. The throw expression normally causes the code to stop or terminate during normal flow of java code.The Throw proceed the controls to nearest catch block. If  there is no catch block, then program terminates.
The Syntax used to declare the throw statement:
throw Throwable objt
The above Syntax ,Throwableobjt is an object of the class Throwable.The Throwableobj object is created  using the new operator.The compiler gives you an error if the throwableobjt does not belong to a valid class of Exception.
The following Example help you to understand  the throw -
class ThrowState
{
static void throwdemostration()
{
try
{
throw new IllegalStateException();
}
catch (NullPointerException objetB)
{
System.out.println("Not caught by catch block inside throwdemostration().");
}
}
public static void main(String args[])
{
try
{
throwdemostration();
}
catch(IllegalStateException objetC)
{
System.out.println("Exception Caught in:"+ objetC);
}
}
}

In the above given code, the new operator create an object of IllegalStateException.In the throwdemostration() method, an exception IllegalStateException is thrown. 
Output of the code in Command Prompt
C:\java>javac ThrowState.java
C:\java>java ThrowState
Exception Caught in:java.lang.IllegalStateException
C:\java>

0 comments:

Post a Comment

 
Top