Total members 11895 |It is currently Sun Dec 22, 2024 11:11 am Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





Java defines several built-in classes for exception handling. All these classes are a part of the java.lang package which is automatically imported. That is why, while throwing an exception you did not specifically include any package for exception classes.

Apart from the built-in exception classes you can define your own exception classes. This is very useful when you want to define exception types which are having a behavior different from the standard exception type, particularly when you want to do validations in your application. The example given below created and used in the same, lava file, but it is possible to create and store exception type in packages and use them elsewhere.

Code:
class NumberRangeException extends Exception
{     
String msg;   
  NumberRangeException()   
{       
  msg = new String("Enter a number between 20 and 100");   
  }
}
public class My_Exception
{   
  public static void main (String args [ ])   
{         try 
       {   
          int x = 10;       
     if (x < 20 || x >100) throw new NumberRangeException( );
        }   
      catch (NumberRangeException e)       
  {   
          System.out.println (e);       
}
    }
}



the output of the code :
Code:
NumberRangeException


The exception class here is the NumberRangeException class. You must have noticed that this class is derived from the exception class. A variable 'msg' of String type is defined and in the constructor it is initialized with appropriate message. You are also overriding the function toString with statement 'System.out.println (e);' so that the caught exception object can convey some message when used in a print statement.



_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 1 post ] 

  Related Posts  to : Creating your own Exceptions in Java
 How to throw Exceptions in Java?     -  
 Creating a JAR file in Java     -  
 creating arrays in java     -  
 Creating a Java Application Build using RAD 7     -  
 creating application for Samsung using java     -  
 What are exceptions and how to handle them!!!     -  
 exceptions catch by a catch clause     -  
 Creating a Directory in php     -  
 Creating table using div tag     -  
 Creating a Method in jsp     -  



Topic Tags

Java Exceptions
cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com