I am trying to create a custom exception in Java, however, I get a compile error when I create the custom exception and try to use it. I have searched through this forum and did not provide much help, because I try to use similar code and it still does not fix the problem!
Here's the code:
class CoogieException extends Exception {
public int numCats;
public String msg;
public CoogieException() {
}
public CoogieException(String msg) {
super();
this.msg = msg;
}
public int getNumCats() {
return numCats;
}
}
and the main class -
public class Lab12 {
public int checkValue(int numCats) throws CoogieException {
if (numCats != (int) numCats) {
throw new CoogieException("Sorry, invalid entry");
} else {
return numCats;
}
}
public static void main(String[] args) {
CoogieException test = new CoogieException();
Scanner in = new Scanner(System.in);
System.out.println("Enter num of cats: ");
int numCats = in.nextInt();
try {
lb = new Lab12();
lb.checkValue(numCats);
} catch (CoogieException co) {
System.out.println("numCats is too many cats!!!!!");
}
}
}
FYI...
Lab12.java:27: error: incompatible types: CoogieException cannot be converted to Throwable
public int checkValue(int numCats) throws CoogieException {
^
Lab12.java:29: error: incompatible types: CoogieException cannot be converted to Throwable
throw new CoogieException("Sorry, invalid entry");
^
Lab12.java:119: error: incompatible types: CoogieException cannot be converted to Throwable
} catch (CoogieException co) {
Probably you have a class somewhere called Exception that doesn't extend java.lang.Exception (or implement Throwable). Also possible you have another class called CoogieException with the same problem.
Related
In the problem I have to check whether a string is equal to "India" or not. If they are not equal then I have to throw an exception "No Match Exception"
I am creating a class nomatchexception and from constructor I am passing a string "America". Then I am checking whether it equals to "India" or not. If both are equal then printing "Matched" otherwise throwing the exception using throw.
class nomatchexception {
String s;
nomatchexception(String s) {
this.s = s;
if (s.equals("India")) {
System.out.print("Matched!\n");
} else {
throw new NoMatchException("Not Matched!\n");
}
}
}
class nomatchex {
public static void main(String[] a) {
nomatchexception v = new nomatchexception("America");
}
}
Error:
nomatchex.java:9: error: cannot find symbol
throw new NoMatchException("Not Matched!\n");
^
symbol: class NoMatchException
location: class nomatchexception
1 error
You have a class nomatchexception that raises your exception, but NoMatchException excepction class does not exist in your code and is not part of java.
It's required to create a class NoMatchException extending exception and with the proper overrides like:
class NoMatchException extends Exception {
public NoMatchException(String message){
super(message);
}
}
And now you are able to raise your NoMatchException exceptions.
Also for good coding is recommended to use the proper case and naming in the classes maybe your nomatchexception class must be calle IndiaAssertComparer or similar.
Complete example:
class NoMatchException extends Exception {
public NoMatchException(String message){
super(message);
}
}
class IndiaAssertComparer {
private String s;
IndiaAssertComparer(String s) throws NoMatchException {
this.s = s;
if (s.equals("India")) {
System.out.print("Matched!\n");
} else {
throw new NoMatchException("Not Matched!\n");
}
}
}
class NoMatcher {
public static void main(String[] a) throws NoMatchException {
IndiaAssertComparer v = new IndiaAssertComparer("America");
}
}
Create a user defined exception named “NoMatchException” that is fired when the string entered by the user is not “india”.
import java.util.Scanner;
class NoMatchException extends Exception{
String s1;
NoMatchException(String s2)
{
this.s1=s2;
}
public String toString()
{
return s1;
}
public static void main(String[] args) {
String s3;
Scanner sc=new Scanner(System.in);
System.out.println("Please enter a string");
s3=sc.nextLine();
try {
if(!"india".equalsIgnoreCase(s3))
throw new NoMatchException("NoMatch
Exceptioncaught!!!");
else {
System.out.println("String matched!!!");
}
}
catch(NoMatchException e) {
System.out.println(e);
}
}
}
I know how to create an exception, but I want to intentionally "break" another class.
Let there be two classes X and Y.
If X is running, how can I create an exception that causes the console to output an exception from Y?
Thanks!
~Java preferred
Edit:
Apparently +MarsAtomic and +Murat K. cannot comprehend English correctly. I asked to throw the exception from ANOTHER class, not the class that is running. I do not understand how people can live in society with such a deficient level of reading comprehension.
throw new RuntimeException();
or
String exceptionMsg = "Error";
throw new RuntimeException(exceptionMsg);
--
public class X
{
public X()
{
Y.CreateException();
//or
Y.CreateException("Error");
}
}
public class Y
{
public static void createException()
{
throw new RuntimeException();
}
public static void createException(String msg)
{
throw new RuntimeException(msg);
}
}
Let there be:
public class thisIsAnException extends Exception{
private Class source;
public thisIsAnException(Class source){
this.source = source;
}
public void setSource(Class source) {
this.source = source;
}
#Override
public String getMessage(){
return "Oh no, there is an exception in: " + source.getName();
}
}
public class Y {
public Y(){
try {
X instanceX = new X();
} catch (thisIsAnException ex) {
ex.setSource(this.getClass());
System.err.println(ex.getMessage());
}
}
public static void main(String[] args){
Y instanceY = new Y();
}
}
public class X {
public X () throws thisIsAnException{
throw new thisIsAnException(this.getClass());
}
}
Is this what you mean?
Jmockit is very powerful, but sometimes I cannot understand what it does behind the scene, so I have a question regarding jmockit. Hopefully the more experienced programmers on here could help shine some light on this situation :)
I have the following two classes in two separate files:
public class SmallClass {
String a;
SmallClass(String arg) throws Exception {
a = arg;
}
public String getString() {
return a;
}
}
And
public class BigClass {
private static final SmallClass smallClass;
static {
try {
smallClass = new SmallClass("dummy");
} catch (Exception e) {
throw new IllegalStateException("Could not initialized", e);
}
}
public static String getString() {
return smallClass.getString();
}
}
Now, I have a class to test BigClass:
public class BigClassTest {
#Test
public void testGet() throws Exception {
///CLOVER:OFF
new MockUp<SmallClass>() {
#Mock
public void $init(String string) throws Exception {
//Do nothing
}
#Mock
public String getString() {
return "dummyString";
}
};
///CLOVER:ON
Assert.assertEquals("dummyString", BigClass.getString());
}
#Test(expected = ExceptionInInitializerError.class)
public void testException() throws Exception {
///CLOVER:OFF
new MockUp<SmallClass>() {
#Mock
public void $init(String string) throws Exception{
throw new Exception("Mocked Exception");
}
};
///CLOVER:ON
BigClass.getString();
}
}
If I run each of these independently, then they each passes. But if I run the whole test file, then the first test fails with:
java.lang.NoClassDefFoundError: Could not initialize class BigClass
I also tried tearing down the mock after each test like this, but it doesn't help:
public class BigClassTest {
MockUp<SmallClass> smallClassMockUp;
#Test
public void testGet() throws Exception {
///CLOVER:OFF
smallClassMockUp = new MockUp<SmallClass>() {
#Mock
public void $init(String string) throws Exception {
//Do nothing
}
#Mock
public String getString() {
return "dummyString";
}
};
///CLOVER:ON
Assert.assertEquals("dummyString", BigClass.getString());
smallClassMockUp.tearDown();
}
#Test(expected = ExceptionInInitializerError.class)
public void testException() throws Exception {
///CLOVER:OFF
smallClassMockUp = new MockUp<SmallClass>() {
#Mock
public void $init(String string) throws Exception{
throw new Exception("Mocked Exception");
}
};
///CLOVER:ON
BigClass.getString();
smallClassMockUp.tearDown();
}
}
Any help would be appreciated. Thank you in advance!
The occurrence of NoClassDefFoundError, in a case like this, is not because the class wasn't found by the JVM (it was), but because its static initialization has failed (by throwing an exception or error from the execution of a static initializer). Once this happens, the class is left in an invalid/uninitialized state and cannot be used in the same JVM instance anymore.
For reference, see the "Initialization of classes and interfaces" section in the JLS.
Also, note that the order in which tests execute is not necessarily the textual order they appear in the test class. Here, testException (the second test) runs first. So, when testGet runs, the class is invalid and the JVM throws the error.
I have defined my own expection class:
public class ProduktException extends Exception {
public ProduktException(String msg){
//null
}
public static void throwProduktNotCreatedException() throws ProduktException {
throw new ProduktException("Cannot be created!");
}
public static void throwProduktNotDeletedException () throws ProduktException {
throw new ProduktException("Cannot be deleted!");
}
}
My Problem is I do not know how to throw them when I try:
try {
...
} catch(ProduktNotDeletedException e) {
e.toString();
}
That does not work... But I want to have these structure! What is wrong?
I appreaciate your answer!!!
UPDATE:
My Problem is, I do not want to create several Exception Klasses I want to have all Exceptions in one class. Is there possibly a solution for that?
If you need to differentiate between different kinds of exceptions, just create 2 different exceptions, maybe something like:
public class ProduktException extends Exception
{
public ProduktException(String msg){
//null
}
}
Then have:
public class ProduktNotDeletedException extends ProduktException
{
....
}
and
public class ProduktNotCreatedException extends ProduktException
{
....
}
Then you can catch one or the other, or both.
try {
...
} catch(ProduktNotDeletedException e1) {
e1.toString();
} catch(ProduktNotCreatedException e2) {
e2.toString();
}
EDIT:
For a single class what I mean is:
public class ProduktException extends Exception {
boolean notDeleted;
boolean notCreated;
public ProduktException(String msg){
super(msg);
}
public boolean isNotDeleted() {
return(notDeleted);
}
public boolean isNotCreated() {
return(notCreated);
}
public static void throwProduktNotCreatedException() throws ProduktException {
ProduktException e = new ProduktException("Cannot be created!");
e.notCreated = true;
throw e;
}
public static void throwProduktNotDeletedException () throws ProduktException {
ProduktException e = new ProduktException("Cannot be deleted!");
e.notDeleted = true;
throw e;
}
}
Then in your try/catch:
try {
...
} catch(ProduktException e) {
e.toString();
if(e.isNotCreated()) {
// do something
}
if(e.isNotDeleted()) {
// do something
}
}
You need to either catch ProduktException, e.g.
try {
...
} catch (ProduktException e) {
e.toString();
}
or declare subtypes, e.g.
public ProduktNotDeletedException extends ProduktException
You'll probably want to pass the message in the constructor up, so add the following in your constructor:
super(msg);
The Syntax given below.
class RangeException extends Exception
{
String msg;
RangeException()
{
msg = new String("Enter a number between 10 and 100");
}
}
public class MyCustomException
{
public static void main (String args [])
{
try
{
int x = 1;
if (x < 10 || x >100) throw new RangeException();
}
catch(RangeException e)
{
System.out.println (e);
}
}
}
What you could do if you don't want to create multiple subclasses of your ProduktException for each different type of exception you need to throw is to include a code in the exception which will let you know what is wrong. Something like this:
public class ProduktException extends Exception {
private Code exceptionCode;
private String message
public ProduktException(Code code, String msg){
this.message = msg;
this.exceptionCode = code;
}
//Getters and setters for exceptionCode and message
}
Code can be an enum so that your application can know that each code corresponds to a specific "problem" (product not created, product not deleted, etc.). You can then throw your exceptions like this
throw new ProduktException(Code.PRODUCT_NOT_CREATED,
"Error while creating product");
And when you catch it you can differentiate based on the code.
catch (ProduktException ex) {
if (ex.getExceptionCode().equals(Code.PRODUCT_NOT_CREATED)) {
...
}
else {
...
}
}
$ javac TestExceptions.java
TestExceptions.java:11: cannot find symbol
symbol : class test
location: class TestExceptions
throw new TestExceptions.test("If you see me, exceptions work!");
^
1 error
Code
import java.util.*;
import java.io.*;
public class TestExceptions {
static void test(String message) throws java.lang.Error{
System.out.println(message);
}
public static void main(String[] args){
try {
// Why does it not access TestExceptions.test-method in the class?
throw new TestExceptions.test("If you see me, exceptions work!");
}catch(java.lang.Error a){
System.out.println("Working Status: " + a.getMessage() );
}
}
}
TestExceptions.test returns type void, so you cannot throw it. For this to work, it needs to return an object of a type that extends Throwable.
One example might be:
static Exception test(String message) {
return new Exception(message);
}
However, this isn't very clean. A better pattern would be to define a TestException class that extends Exception or RuntimeException or Throwable, and then just throw that.
class TestException extends Exception {
public TestException(String message) {
super(message);
}
}
// somewhere else
public static void main(String[] args) throws TestException{
try {
throw new TestException("If you see me, exceptions work!");
}catch(Exception a){
System.out.println("Working Status: " + a.getMessage() );
}
}
(Also note that all classes in package java.lang can be referenced by their class name rather than their fully-qualified name. That is, you don't need to write java.lang.)
Working Code
Try this:
public class TestExceptions extends Exception {
public TestExceptions( String s ) {
super(s);
}
public static void main(String[] args) throws TestExceptions{
try {
throw new TestExceptions("If you see me, exceptions work!");
}
catch( Exception a ) {
System.out.println("Working Status: " + a.getMessage() );
}
}
}
Problems
There are a number of issues with the code you posted, including:
Catching Error instead of Exception
Using a static method to construct the exception
Not extending Exception for your exception
Not calling the superclass constructor of Exception with the message
The posted code resolves those issues and displays what you were expecting.