Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Exception

Posted on 2001-06-28
8
Medium Priority
?
315 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 2

Accepted Solution

by:
barrel earned 80 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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

Tech or Treat! - Giveaway

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
The viewer will learn how to implement Singleton Design Pattern in Java.
This video teaches viewers about errors in exception handling.
Suggested Courses

610 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