Unhandled exception type in JAVA

I have two classes in one package in JAVA.

One class in which I have a constructor, an exception that I tried to create myself:

public class ZooException extends Exception { public ZooException(String error) { super(error); } } 

Another class should throw this exception at one point:

 public class Zoo<T extends Animal> Zoo(int capacity) { if (capacity <= 1) { throw new ZooException("Zoo capacity must be larger than zero"); } } 

I notice two things here.

  • In the ZooException class, I get a warning: "The CageException serializable class does not declare a static final field serialVersionUID of type long"
  • In the Zoo class, in the line starting with "throw new", I get a compilation error: "Unhandled exception type CageException"

Any ideas on what I can do to solve this error in the Zoo class? Thank you in advance!

+4
source share
3 answers

You are extending the Exception , the checked exception, this means that any method that throws this exception should say so:

 Zoo(int capacity) throws ZooException { 

And any code that calls this constructor will have to try {} catch {} or throw it again.

If you don't want it checked, use extends RuntimeException instead

+11
source

About Exceptions @Will P is right.

About serialVersionUID, this means - because Exception is Serializable - if you decide at any time that the previous version of your class should not be compatible with your newer version (usually for public APIs), for example, this class has undergone major changes, just change the unique identifier , and reading the object of the old version will throw an exception.

+1
source
 Zoo(int capacity) throws ZooException { if (capacity <= 1) { throw new ZooException("Zoo capacity must be larger than zero"); } 

You must declare checked exceptions or handle them with a try-catch bock. Try reading on exceptions: http://docs.oracle.com/javase/tutorial/essential/exceptions/

0
source

Source: https://habr.com/ru/post/1484059/