Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 322
  • Last Modified:

Exception

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
mca1
Asked:
mca1
1 Solution
 
barrelCommented:
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
 
rxolotlCommented:
//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
 
scientist060700Commented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
barrelCommented:
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
 
scientist060700Commented:
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
 
barrelCommented:
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
 
scientist060700Commented:
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
 
SpideyModCommented:
Force Accepted

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now