Solved

Exception

Posted on 2001-06-28
8
301 Views
Last Modified: 2013-12-29
CAn we define new Exception.that is user defined exception ?
IF a statemetn is error then it throws some exception,or it throw some exception and catch it my the mehtod.
cam we decalare our own exception and can we catch it?
0
Comment
Question by:mca1
8 Comments
 
LVL 2

Accepted Solution

by:
barrel earned 20 total points
ID: 6234761
Yes we can write our own exceptions, just let your exception extend the java.lang.Exception class

For instance:

public class AssertException extends java.lang.Exception {

  private int id;
  private String message;

  /*
   * Identifiers
   */
  public static final int ASSERT = 0;
  public static final int     REQUIRE = 1;
  public static final int     ENSURE = 2;
  public static final int     CHECK = 3;
 
  /**
   * The constructor of this exception class
   */
  public AssertException (int id)
  {
    this.id = id;
  }

  /**
   * The constructor of this exception class
   */
  public AssertException (int id, String aMessage)
  {
    this.id = id;
    this.message = aMessage;
  }

  /**
   * returns the ID of this exception
   */
  public int getId ()
  {
    return id;
  }

  /**
   * Returns the message that belongs to the Exception
   */
  public String getMessage ()
  {
    return this.message;
  }
}


And he assert class catches throws these exceptions when something is wrong:


public class Assert {

  /**
   * This class should not be instantiated
   */
  private Assert () {}

  /**
   * An intermediate check
   * If the condition fails, an appropriate exception is thrown
   */
  public static void check (boolean condition)
    throws AssertException
  {
    if (!condition)
    {
      throw new AssertException (AssertException.CHECK);
    }
  }

  /**
   * An intermediate check
   * If the condition fails, an appropriate exception is thrown containing
   * the message.
   */
  public static void check (boolean condition, String message)
    throws AssertException
  {
    if (!condition)
    {
      throw new AssertException (AssertException.CHECK, message);
    }
  }
// etc
}


Now in your code, do something like

public void myFunction (int i)
{
    try
    {
        Assert.check (i > 10, "Check on i > 10 failed");
    }
    catch (AssertException ae)
    {
        // do what you feel is necessary
    }
    // and the rest of the code
}

Of course, this is public class Assert {

Barrel
0
 
LVL 1

Expert Comment

by:rxolotl
ID: 6236290
//User Handler Example
public void exe()throws MyEX{

//trowing a user exception
MyEX myEx = new MyEX("Error: 10 Working wrong\n");
throw myEx;

}

----------------------------------------
public class  MyEX extends Exception
{  
     public MyEX(){}
     public MyEX(String msg){super(msg);}
   
}
0
 
LVL 1

Expert Comment

by:scientist060700
ID: 6241266
for the most of the exceptions thrown in java, if you are using try-catch block you may write catch (exception e)
you do not have to define exceptions in to the try-catch blocks.  Of course, if you know which exception will occur you can define but it is not rule for java to define the exception.
--hope it helps
--scientist
0
 
LVL 2

Expert Comment

by:barrel
ID: 6258628
Scientist,

You mention yourself that you hope your input helps, why block it by proposing an answer?

Here is some text from the book "Thinking in Java" which should clarify some things:

To create your own exception class, you?re forced to inherit from an
existing type of exception, preferably one that is close in meaning to your
new exception (this is often not possible, however). The most trivial way
to create a new type of exception is just to let the compiler create the
default constructor for you, so it requires almost no code at all:


//: c10:SimpleExceptionDemo.java
// Inheriting your own exceptions.
class SimpleException extends Exception {}
  public class SimpleExceptionDemo {
    public void f() throws SimpleException {
      System.out.println("Throwing SimpleException from f()");
      throw new SimpleException ();
    }

    public static void main(String[] args) {
      SimpleExceptionDemo sed = new SimpleExceptionDemo();
      try {
        sed.f();
      } catch(SimpleException e) {
        System.err.println("Caught it!");
      }
    }
   } ///:~


When the compiler creates the default constructor, it which automatically
(and invisibly) calls the base-class default constructor. Of course, in this
case you don?t get a SimpleException(String) constructor, but in
practice that isn?t used much. As you?ll see, the most important thing
about an exception is the class name, so most of the time an exception like
the one shown above is satisfactory.
Here, the result is printed to the console standard error stream by writing
to System.err. This is usually a better place to send error information
than System.out, which may be redirected. If you send output to
System.err it will not be redirected along with System.out so the user
is more likely to notice it.
Creating an exception class that also has a constructor that takes a String
is also quite simple:


//: c10:FullConstructors.java
// Inheriting your own exceptions.
class MyException extends Exception {
  public MyException() {}

  public MyException(String msg) {
    super(msg);
  }
}

public class FullConstructors {
  public static void f() throws MyException {
    System.out.println( "Throwing MyException from f()");
    throw new MyException();
  }

  public static void g() throws MyException {
    System.out.println("Throwing MyException from g()");
    throw new MyException("Originated in g()");
  }

  public static void main(String[] args) {
    try {
      f();
    } catch(MyException e) {
      e.printStackTrace(System.err);
    }
    try {
      g();
    } catch(MyException e) {
      e.printStackTrace(System.err);
    }
  }
} ///:~


The added code is small?the addition of two constructors that define the
way MyException is created. In the second constructor, the base-class
constructor with a String argument is explicitly invoked by using the
super keyword.

The stack trace information is sent to System.err so that it?s more likely
it will be noticed in the event that System.out has been redirected.

The output of the program is:

Throwing MyException from f()
MyException
    at FullConstructors.f(FullConstructors.java:16)
    at FullConstructors.main(FullConstructors.java:24)
Throwing MyException from g()
MyException: Originated in g()
    at FullConstructors.g(FullConstructors.java:20)
    at FullConstructors.main(FullConstructors.java:29)

You can see the absence of the detail message in the MyException
thrown from f( ).
The process of creating your own exceptions can be taken further. You can
add extra constructors and members:

//: c10:ExtraFeatures.java
// Further embellishment of exception classes.
class MyException2 extends Exception {
  public MyException2() {}

  public MyException2(String msg) {
    super(msg);
  }

  public MyException2(String msg, int x) {
    super(msg);
    i = x;
  }

  public int val() { return i; }
  private int i;
}

public class ExtraFeatures {
  public static void f() throws MyException2 {
    System.out.println("Throwing MyException2 from f()");
    throw new MyException2();
  }

  public static void g() throws MyException2 {
    System.out.println("Throwing MyException2 from g()");
    throw new MyException2("Originated in g()");
  }

  public static void h() throws MyException2 {
    System.out.println("Throwing MyException2 from h()");
    throw new MyException2("Originated in h()", 47);
  }

  public static void main(String[] args) {
  try {
    f();
  } catch(MyException2 e) {
    e.printStackTrace(System.err);
  }
  try {
    g();
  } catch(MyException2 e) {
    e.printStackTrace(System.err);
  }
  try {
    h();
  } catch(MyException2 e) {
    e.printStackTrace(System.err);
    System.err.println("e.val() = " + e.val());
  }
}
} ///:~

A data member i has been added, along with a method that reads that
value and an additional constructor that sets it. The output is:

Throwing MyException2 from f()
MyException2
    at ExtraFeatures.f(ExtraFeatures.java:22)
    at ExtraFeatures.main(ExtraFeatures.java:34)
Throwing MyException2 from g()
MyException2: Originated in g()
    at ExtraFeatures.g(ExtraFeatures.java:26)
    at ExtraFeatures.main(ExtraFeatures.java:39)
Throwing MyException2 from h()
MyException2: Originated in h()
    at ExtraFeatures.h(ExtraFeatures.java:30)
    at ExtraFeatures.main(ExtraFeatures.java:44)
e.val() = 47

Since an exception is just another kind of object, you can continue this
process of embellishing the power of your exception classes. Keep in
mind, however, that all this dressing-up might be lost on the client
programmers using your packages, since they might simply look for the
exception to be thrown and nothing more. (That?s the way most of the
Java library exceptions are used.)
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Expert Comment

by:scientist060700
ID: 6262110
Thanks for the big comment barrel But my proposed answer also comes from the Book "Java Programmimg :From the Beginning" and I have just completed highly recommended  course in java using that book so, I have some knowledge of what is a good answer or good comment.
--scientist
0
 
LVL 2

Expert Comment

by:barrel
ID: 6263906
If you read the guidelines, you will see that it is not seen as appropriate to post an answer to a question, but post a comment. The one who posted the question can reward comments afterwards.

I did not say that your input was not correct, I just think it is not totally complete :O)

Cheers,
Barrel
0
 
LVL 1

Expert Comment

by:scientist060700
ID: 6264879
I will leave that decision to the grader of the answer. If the mca1 feels that the solution is not complete, s/he has right to reject my answer or ask for more explanation.
--scientist.
0
 

Expert Comment

by:SpideyMod
ID: 8289494
Force Accepted

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now