RunTime custom exceptions

So, this is about the interview question that I recently asked. The interviewer started by asking me how we create our custom Exceptions. In response to this, he asked me how I create RunTimeExceptions. I said that we will create them in the same way as we create verified Exceptions. It’s just that our custom exception will extend to the RunTimeException class. He then asked in which scenarios you would throw your own RunTimeException. Now I could not come up with a good answer to this question. In none of my projects have we created custom RunTimeExceptions.

I also think that we should never create RunTimeExceptions. The JVM can only fail in a finite number of ways, and it handles them well. When writing an application, we cannot predict which runtime exceptions may occur, and therefore we do not need to handle them. And if we can predict these conditions, then they are not RunTimeExceptions. Since we don't need new runtime exceptions, nor the need to handle runtime exceptions, why would we ever need to throw a custom RunTimeException. Everything that we can predict as a possible failure condition must be handled at compile time, and this will be a checked exception. Right? Only those things that cannot be processed at compile time, and those that depend on runtime, are included in the RunTimeExceptions category.

Even if we write custom RunTimeExceptions, and then a custom method that should throw a RunTimeException - how do we make sure that the method will throw this particular RunTimeException. How do we do it. It seems impossible to me.

Did I miss something / many things here? Request for advice.

Thanks, Chan.

+4
source share
4 answers

I think the interviewer was trying to figure out if you understand the purpose of runtime exceptions that should signal programmer errors (as opposed to application exceptions that signal runtime problems).

You can and should subclass RuntimeException when your method needs to signal a state that is a programming error, and you need to provide additional information about the error described in the description.

For example, consider a class that allows you to store data in a sparse multidimensional array. One of the APIs that is likely to provide such a class is getter, which accepts an array of indices. The number of indices must be equal to the number of dimensions in the array, and each index must be within its boundaries. Delivering an array parameter that has the wrong number of elements or has one or more elements outside its boundaries is a programming error. You should signal this with a runtime exception. If you want to report this error and provide complete information about what went wrong, your subclass of IllegalArgumentException , a subclass of RuntimeException , to throw your own exception.

Finally, there is another situation where you want to subclass RuntimeException : when you must provide a “regular” exception, but you do not want your users to wrap every call to your API with try / catch . In situations like this, you can replace one method.

 void performOperation() throws CustomApplicationException; 

using a couple of methods

 boolean canPerformOperation(); void performOperation(); 

The first method tells the caller that it is safe to call the second method in its current state; it never throws an exception.

The second method fails only in the state where the first method returns false , which makes the failure a programming error, thereby justifying the use of a RuntimeException to signal such failures.

+6
source

Checked Exception vs Unchecked Exception is a long time discussion among Java developers. I will not be here to make a fire, but I want to share with you how I use it in our work.

For example, another service calls my server for client information. The login is customerID and I will return the customer object

 // Web Service interface public CustomerInfo getCustomerInformation(int customerId, int securityToken) { check(securityToken); Customer customer = merchantService.getCustomer(customerId); return customer.getInfo(); } // MerchantService public Customer getCustomer(int customerId) { return customerService.getCustomer(customerId); } 

What happens if the system cannot find a specific client? Of course, it will throw an exception or return null. But returning a null value is bad, as it will force you to check null every time you call from a service. So I go with the exception:

 // Customer service public Customer getCustomer(id) { Customer customer = getCustomerFromDB(); if (customer == null) throw CustomerNotExistedException(); return customer; } 

Now the question is whether CustomerNotExistedException is a RuntimeException or an exception. If this is a checked exception, you need to catch and handle it using a function that calls getCustomer . That means you have to catch it in a MerchantService. However, all you need to do is create a 404 error at the WebService level, so catching it in the MerchantService will do nothing but throw an exception. It pollutes the code.

In general, I often use RuntimeException to throw an “exception” to the level at which they can be handled.

For your reference, I would recommend the book Clear Code from Robert C. Martin . This explains how we should use exception to handle errors in Java.

+4
source

You would create your own RuntimeException subclass if:

  • You do not want this to be a checked exception, because you do not expect callers to explicitly understand the exception. (Personally, I believe that checked exceptions are more likely to be used in the standard library.)
  • You still want to provide more information than just a message (only the type itself is a useful starting point in the log).

HibernateException is an example of this in Hibernate ORM.

+1
source

I think that when creating custom exceptions, please do not subclass RuntimeException , it defeats the goal of creating a custom exception.

Even if we write custom RunTimeExceptions, and then a custom method that should throw a RunTimeException - how do we make sure that the method will throw this particular RunTimeException.

In this case, we are talking about the fact that the calling method should not surround it in the try-catch , since it is not a checked exception. Unless you have a good reason to throw the usual excluded exception, say just provide additional custom information for logging, etc., don’t do this. Another unsuccessful implementation will sometimes be that you just want to catch checked exceptions in your code and throw arbitrary unchecked exceptions to get rid of all attempts in the caller's code.

0
source

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


All Articles