Java defining custom exceptions inside of class, is this bad? - java

I have a class that has a method. The method may fail and I want to throw an exception. Is it bad to define the exception class within the namespace of the class whose function is throwing the exception? I haven't seen a lot of examples of this, but it seems like the "right" (i.e. OO) way to do it? Is there a reason I should avoid this pattern and define each custom exception in its own file?
public class Foo
{
void bar() {
// do something and throw BarException if something bad happens
}
public static class BarException extends Exception {
// rest of class definition
}
}

I think it depends on the possible scope of the Exception you're creating. If it will only have to do with Foo, and only Foo, forever, then creating it as a nested class would be good.
Just make sure it makes sense for something calling Bar to say:
catch (Foo.BarException e)
instead of
catch (BarException e)
Else, create it as its own standalone class.
As for the namespace, a Java class could be used for namespacing classes, but generally in Java packages are used for namespacing your classes. I would only use a nested class if there is a very high coupling between the main class and the other class.

I would not use this pattern.
You add more line to class.
This class has more than one concern
and you will get problems, if you want to use the same Exception in another class.
Why do you want to do this? Just, because you don't want to create a new file? ;)
In Java you should only ad one public class in one file. Sometimes I add public interfaces into classes, most for event handling.
class MyEvent {
public void registerHandler(MyEvent.Handler h){
//
}
public interface Handler(){
handle();
}
}
In this case I am absolute sure, there wont be any other class using this Interface.

Related

why exception is a class and not a interface in java?

As we all know exception is a by default class and exception class extends Throwable.
My question is: why exception is not a interface ?
if we will try to mold exception class as interface it will show error. i tried it out but still i am not able to find a exact reason for the same.
this is a code I tried:
Interface:
package com.prg;
import com.thed.util.CustomException ;
public interface ExceptionInterface extends Throwable{
public String sayHello() throws CustomException {
return null;
}
}
Class:
package com.prg;
import com.thed.util.CustomException ;
public class ExceptionCheck implements ExceptionInterface {
public String sayHello() {
return "Hey";
}
public ExceptionCheck() throws CustomException {
System.out.println("hi");
}
public static void main (String[] args) throws CustomException {
System.out.println("how are you");
throw new ExceptionInterface({
public String sayHello() { return "Hey"; }
});
}
}
If i am changing interface to class then it is not showing exception which is expected. but why not interface this is my question ?
Simple: because there is quite a lot of implementation code to be found within the Throwable class which is the base of the whole hierarchy. And as one comment reminds us: there is also a lot of exception related code backed into the native parts of the JVM - and it would be probably very hard if that code had to deal with arbitrary objects implementing an Exception interface.
There is no point in using interfaces when you want to give a core library element to your users that includes implementation.
( keep in mind that default methods - aka method bodies - weren't allowed in Java until Java8 !)
Beyond that: interfaces are useful to allow different "views" on classes. In other words: Integer for example can be seen as Comparable. There might be situations where it is perfectly fine to only address an Integer object as a Comparable. But the true essential nature of Integer is still: it is a class representing a whole number of a certain range.
Now think about exceptions! What would be the conceptual "sense" in having public class Foo implements Exception? What would Foo be about "without" that exception view?! In other words: exceptions are also conceptually "important" enough to stand as distinct classes!
Keep in mind that classes and interfaces exist to model abstractions. Maybe I am just not creative enough - but I do not see how something could be a Foo object - but also, if required be an exception.
Finally: a class is a class, and an interface is an interface. Those are different things. And the only relation that is allowed is: classes extend classes, and can implement interfaces. Interfaces can only extend other interfaces. That is simply how the Java language is designed - and there is no way of doing what you code implies you want to do.

Run-time class instantiation based on external xml in Java

I have an xml file that contains data I want to parse and read into my program so i can instantiate a class.
The problem is, which class i want to instantiate wont be known until runtime.
My xml will be a little like below.
<dataitem class="FooClass">
<dataitem class="BarClass">
Classes will all share a common interface.
At the moment i have Factory doing something like below.
public class FooBarFactory {
FooBarInterface makeClass(String s){
if(s.equals("FooClass")){
return new FooClass();
}
if(s.equals("BarClass")){
return new BarClass();
}
}
In reality, there are a great many potential classes the Factory could return. Is there a way to get this sort of behaviour without having to use a conditional statement for each potential class it could be? If not, is my thinking correct or is there a better way of doing this?
public class FooBarFactory {
FooBarInterface makeInstance(String s) {
return Class.forName(s).newInstance();
}
}
I didn't show it, but you will need to handle some checked exceptions such as ClassNotFoundException, IllegalAccessException, and InstantiationException.

Spring:DI with interface with implementation class less restrictive exceptions

I have an implementation class which catches all the declared exceptions of a method of an Interface. As I inject and use the Interface instance variable inside a class and hope to call the implementation method - I am naturally getting a compiler error pointing that I either need to throw/catch the exceptions declared in parent.
Few options that come to my mind are these, but I don't like them. Just want to know the best way to go about this.
Cast the interface instance to impl
Create child interface with a method with no exceptions
May be just not declare exceptions in Interface. Just catch all of the possible exceptions in impl.
EDIT 1: Attached some example code
public interface ServiceUtilInterface {
public abstract String getMessage(String ID) throws CustomException;
}
#Component(value="MyServiceUtil")
public class MyServiceUtil implements ServiceUtilInterface {
#Override
public String getMessage(String ID) {
try{
//do something
}catch(CustomException e){
}
return "";
}
#Component
public class Usage {
#Autowired
ServiceUtilInterface serviceUtil;
public void someMethod(){
serviceUtil.getMessage("123");
//This where compiler expects me to throw /catch the exception defined in interface
}
}
UPDATE
Cast the interface instance to impl - never ever do that. If you use Spring then you never know what the implementation of an interface could be. This should be configuration dependent.
If you start do write jUnits you will probably need to use mock (fake) components for testing. Then if you try to cast your mock to a concrete implementation your code will fail. In other words you will never be able to write proper unit tests. The other thing is that if you add some Aspects or make a service #Transactional or #Validated then you wont be able to cast because instead of your implementation you may receive a proxy object.
and 3 that strongly depends on your code design. Try to find some materials about good practices for throwing and handling exceptions. There are some general rules about that. Probably no one can help you with this because this is service specific.

How to force putting a object into a handler class

I already post some relevant code in this question:
Specify object type of a returned array list dynamically
Now my question is a little bit more specific.
In fact I am using the following "handler" class to invoke methods of classes which implement the interface IMSSQLStatement:
public class MSSQLHandler {
IMSSQLStatement statement;
public MSSQLHandler(IMSSQLStatement statement) {
this.statement = statement;
}
public void invoke() throws SQLException {
statement.executeStatement();
}
public List<?> getDataList() throws SQLException {
return statement.getDataList();
}
}
The question is now how to force me (or an developer which implements my interface) to put created objects of the implemented class to MSSQLHandler?
Maybe this is bad design but I did not find any information and use cases regarding my problem.
Yes, you can use an abstract class with an explicit constructor, that is automatically called on all subclasses:
public abstract class IMSSQLStatement {
protected IMSSQLHandler handler;
public IMSSQLStatement() {
handler = new IMSSQLHandler(this);
}
}
Edit: (in reference to comment)
If you want that only the handler should be able to call the methods in IMSSQLStatement, both classes should be placed in the same package. Allow only package-private and subclass access, by giving the protected modifier. Although the methods could be called in the subclass itself, it would not be accessible outside, with the exception of the package.
This won't solve your problem completely. The other (real bogus) way around would be reflection.
To use reflection, you should write in your documentation the exact method signature the subclass should use (of course, don't define an abstract method in the superclass), giving it the private modifier. The handler should access these methods through reflection.
Refer some document, that describes how to use reflection. This is complicated, and beyond the scope of SO.

adding functions to main class from a different class using bean configuration if possible

I'm writing a red5 application in Java. it just means that I have a bean that points to my main class app class that's called Application.
I have several classes that I want to add and remove like modules to my application.
example:
I have two classes called 'A' and 'B', each one of them contains the public function testme().
I want somehow to configure that my main Application class will call the constructor of these two classes and that somehow my main Application class will contains the functions Atestme() and Btestme() that will call the appropriate testme() function in the appropriate class. is there a way to achieve such a thing without me manually creating these functions and calling the appropriate function within one of the classes?
Is there a way to use bean configuration to achieve such a goal ? (I want to be
able to configure adding and removing 'modules' using bean configuration if possible)
I started reading about reflections, and it says that adds performance overhead and I should avoid for production environments that are time and cpu sensitive.
is there a way to catch when aDoTest() or bDoTest() is called in my main class and to catch it in order to call the appropriate functions ?
How about this:
public class Application {
public static void aDoTest() {
doTest(new A());
}
public static void bDoTest() {
doTest(new B());
}
private static doTest(Testable t) {
t.testMe();
}
public static void main(String[] args) {
aDoTest();
bDoTest();
}
}
public interface Testable {
public void testMe();
}
public class A implements Testable {
public void testMe() {
// ...
}
}
If this does not help, you need to clarify your question.
Perhaps you are wanting to catch calls to non-existent (i.e. undeclared or unimplemented) methods and turn them into calls to real methods. If so, you can give up on that idea. Java won't let you do it.
The closest that you can come is to generate a new class at runtime with implementations for this methods:
You can dynamically generate source code, compile it and load it.
You can use something like BCEL to create ".class" files and load them.
Use the Proxy class to create a dynamic proxy implementation of some interface.
But these approaches are all complicated and expensive. (Probably a lot more expensive that using reflection, unless the generation cost can be amortized over a huge number of calls.)
In Java you have methods, not functions.
Write an interface Testable.
public interface Testable {
public void testme();
}
class A and B must implement interface Testable.
Then in your class Application you have a method
private static doTest(Testable t) {
t.testme();
}
and then you have main() method
public static void main(String[] args) {
doTest(new A());
doTest(new B());
}

Categories

Resources