SOME STANDARD THEORY AND INTRODUCTION :
USING THE THROWS :
A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions,except those of type Error or RuntimeException, or any of their subclasses. All otherexceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result.
USING THE THROW :
If the user wants to throw an explicit Exception , often customized , we use the Throw. The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
this can be handled in the same module as shown using the try..catch locally:
or can be further thrown using the THROWS
and should be handled by super function.
A SAMPLE EXAMPLE :
Consider a User-Defined Exception Class as shown below :
The Class has provision for two constructors , one to print any explicit message that was set by the user upon occurrence of any exception , second , in case the user doesn't supply a exception message and the default needs to be printed.
This is where the Exception gets thrown from. We either supply a Exception Message explicitly or can simply invoke the default CredentialException() constructor to use the default message as shown in the previous code snippet. Provided below is the complete code :
- Exceptions are the customary way in Java to indicate to a calling method that an abnormal condition has occurred.
- In Java, exceptions are objects. When you throw an exception, you throw an object. You can't throw just any object as an exception, however -- only those objects whose classes descend from Throwable. Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw.
- Throwable has two direct subclasses, Exception and Error.
- Exceptions (members of the Exception family) are thrown to signal abnormal conditions that can often be handled by some catcher, though it's possible they may not be caught and therefore could result in a dead thread.
- An Unchecked Exception inherits from RuntimeException (which extends from Exception). The RuntimeException gets special treatment from the JVM and there is no requirement for the application-code to deal with them (hence the name Unchecked Exceptions).
- A Checked Exception inherits from the Exception-class. The client code has to handle the checked exceptions either in a try-catch clause or to hand it out to a higher context. A Checked Exception thrown by a lower layer enforces a contract on the invoking layer to catch or throw it. Developers often take shortcuts by suppressing the exception in an empty try-catch block or just throwing it, and thus forwarding the problem to the application's invoker.
- Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle. Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself.
- To create your own class of throwable objects, you need only declare it as a subclass of some member of the Throwable family. In general, however, the throwable classes you define should extend class Exception.
- If one of your methods is invoked with an invalid argument, you could throw IllegalArgumentException, a subclass of RuntimeException in java.lang.
- Any statement placed after the catch block would be unconditionally executed.
try{ ................... return str; //Not reachable if we get exception.So wrong }catch(Exception e) {...}finally{ return str; //OK } return str; //OK
USING THE THROWS :
A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions,except those of type Error or RuntimeException, or any of their subclasses. All otherexceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result.
public void myMethod() throws PRException {..}
This means the super function calling the function should be equipped to handle this exception.
public void Callee() { try{ myMethod(); }catch(PRException ex) { ...handle Exception.... } }
USING THE THROW :
If the user wants to throw an explicit Exception , often customized , we use the Throw. The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
if(age>100){ new AgeBarException(); }else{ ....}
try{ if(age>100){ throw new AgeBarException(); }else{ ....} } }catch(AgeBarException ex){ ...handle Exception..... }
public void CheckAge() throws AgeBarException{
if(age>100){
throw new AgeBarException();
}else{
....}
}
}
A SAMPLE EXAMPLE :
Consider a User-Defined Exception Class as shown below :
class CredentialException extends Exception{ String myerror; /*Default Constructor to handle cases where Custom Exception Message isn't * provided*/ public CredentialException() { super(); this.myerror="Exception due to Unknown Cause"; } /*Parameterized Constructor to Handle Cases where Custom Exception Message * has been supplied by the user.*/ public CredentialException(String msg) { this.myerror=msg; } public String getError() { return myerror; } }
public void CheckCredentials(String userName,String userPwd) throws CredentialException { if((userName.equalsIgnoreCase("soham"))&& (userPwd.equalsIgnoreCase("deep"))) System.out.println("A Very Warm Welcome :: "+userName); else /* * Customized Exception Message.In case we hadn't * provided any Exception String here. The default * constructor would be invoked and 'Exception due * to Unknown Cause' would be printed upon invocation * of the 'getError()' method. */ throw new CredentialException("Invalid Username and Password"); }
package com.soham.Exceptions; import java.io.BufferedReader; import java.io.InputStreamReader; public class CustomizedExceptionPOC { String msg; String username; String password; public void CheckCredentials(String userName,String userPwd) throws CredentialException { if((userName.equalsIgnoreCase("soham"))&& (userPwd.equalsIgnoreCase("deep"))) System.out.println("A Very Warm Welcome :: "+userName); else /* * Customized Exception Message.In case we hadn't * provided any Exception String here. The default * constructor would be invoked and 'Exception due * to Unknown Cause' would be printed upon invocation * of the 'getError()' method. */ throw new CredentialException("Invalid Username and Password"); } public static void main(String[] args) { CustomizedExceptionPOC custExpObj=new CustomizedExceptionPOC(); InputStreamReader ss=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(ss); //Default Exception Handling try { System.out.println("PLEASE ENTER THE LOGIN USERNAME:"); custExpObj.username= br.readLine(); System.out.println("PLEASE ENTER THE LOGIN PASSWORD"); custExpObj.password=br.readLine(); } catch (Exception e) { System.out.println("This is a standard I/O Exception."); } try { custExpObj.CheckCredentials(custExpObj.username,custExpObj.password); } catch(CredentialException custexp) { /* * The Exception is handled out here and the message associated * with the Exception object printed.If an explicit Exception Message * was set , it shall be printed.Else the default would be printed. */ System.out.println("Customized Exception Catch Block Message - "+custexp.getError()); } } } class CredentialException extends Exception{ String myerror; /*Default Constructor to handle cases where Custom Exception Message isn't * provided*/ public CredentialException() { super(); this.myerror="Exception due to Unknown Cause"; } /*Parameterized Constructor to Handle Cases where Custom Exception Message * has been supplied by the user.*/ public CredentialException(String msg) { this.myerror=msg; } public String getError() { return myerror; } }
No comments:
Post a Comment