How can i catch exceptions in a method that throws them(JAVA)? - class

I have a class with a method that throws some exceptions and catches them inside itself, but when i call it in my Main class they seem to not being catched.
An example about my problem:
public class Test {
public static void method (int number) throws InvalidNumberException {
try {
if (number == 5) {
throw new InvalidNumberException("Invalid number");
}
} catch (InvalidNumberException inv) {
System.out.println(inv);
}
}
}
public class InvalidNumberException extends Exception {
public InvalidNumberException (String s) {
super(s);
}
}
public class Main {
public static void main(String args[]) {
Test.method(5);
}
}
When i try to compilate the last one i get this error:
Main.java:3: error: unreported exception InvalidNumberException; must be caught or declared to be thrown
Test.method(5);
Is there a way to fix it without catching the exception in the Main class?

Because you're catching the InvalidNumberException inside of method, there's no need for a throws clause, however, the existence of it mandates that calls to it must handle the exception. Thus, the compiler is expecting you to handle the exception in main.
To solve this, simply remove the throws clause modifying method, since you're already handling the exception inside.

Related

Mock an Interface with Mockito return a NullPointerException

I m trying create unit tests for one project.I m facing a problem because when I try control the result of an interface(mock). When the code get the Interface variable that return a NullPointerException.
Firstly I tried #Override the method in my test class (ClassA), but it don't work. After that I tried mock the interface object and control the comportment with Mockito.When().tehnReturn();
I will put here my code, I read some solutions but none works.
My Interface:
#FunctionalInterface
public interface Interface {
UpdateXResponse process(UpdateXRequest request) throws Exception;
}
The class I want to test:
#Service(ClassA.class)
public class ClassA extends VService implements UpdateX {
#Reference
#Inject
private Interface interface;
#Inject
public ClassA(...) {...}
#Override
public UpdateXResponse process(UpdateXRequest request) throws Exception {
UpdateXResponse response = initResponse(context, request, new UpdateXResponse());
UpdateXInput input = request.getInput();
UpdateXOutput output = new UpdateXOutput();
response.setOutput(output);
try {
firstMethodCall(...);
} catch (Exception t) {
throwCorrectException(t, logger);
}
return response;
}
private void firstMethodCall(...) throws Exception {
TypeF typeF = callInterfaceMethod(...);
...
}
/**
* Orchestrates Interface service
*/
protected TypeF callInterfaceMethod(...) {
...
request.setInput(input);
request.setHeader(header);
InterfaceResponse response = interface.process(request); // LINE ERROR - In this step interface is NULL when the test get this
return response;
}
}
And finally my class test:
#RunWith(PowerMockRunner.class)
#PrepareForTest(value = {ClassA.class,Interface.class} )
public class WithPowerMockUnitTest{
#InjectMocks
private ClassA classA;
private Interface interface;
#Before
public void setUp() throws Exception {
InterfaceRequest InterfaceRequest = createInterfaceRequest();
InterfaceResponse serviceUnavailableResponse = createInterfaceResponse();
Interface = Mockito.mock(Interface.class);
when(Interface.process(Mockito.any(InterfaceRequest.class))).thenReturn(serviceUnavailableResponse);
}
#Test
public void testh() throws SOAException {
InterfaceResponse res = interface.process(Mockito.any(InterfaceRequest.class)); // There all run ok. The interface is not null and return what i expected.
System.out.println("RES "+res);
}
#Test
public void test() {
assertNotNull(classA); // not null
assertNotNull(interface); // not null
}
#Test
public void newTest() throws Exception {
InterfaceRequest InterfaceRequest = createInterfaceRequest();
InterfaceResponse serviceUnavailableResponse = createInterfaceResponse();
UpdateXResponse response = ClassA.process(updateXRequest()); // PROBLEM!! When that get the LINE ERROR the interface is null! WHY?
}
}
I put some comments in the lines where the problem exists for me.
public interface A{
Response process(Request r) throws Exception;
}
public class B{
private Class_That_Override_Interface_method ctoim;
public Response function(){
X res = method_B();
}
protected X method_B(){
response res = ctoim.process(request); // That ctoim is always NULL when the test get that line/call
}
}
Thanks
You're missing the #Mock annotation on your Interface variable.
Therefore the mock is not injected into your classA and the newTest() fails. (In this case remove Interface = Mockito.mock(Interface.class); from the setUp method).
Alternativly remove the #InjectMocks annotation and create your class under test manually passing your mock into the constructor.
For this specific case (assuming its a different case from the last question)
there doesn't seem to be a need to involve PowerMockito. So unless you left out some relevant parts you might as well just use the MockitoJUnitRunner.
Ps.:
Also remeber what I said last time about compilable examples?
interface is a keyword and can't be used for variables.
You should also aim to write variables identical all the times (not Interface and interface / classA and ClassA)
And in case you haven't read it yet check out the help section about minmal reproducible examples.
Edit:
I fogot to mention that the line interface.process(Mockito.any(InterfaceRequest.class)); in testh() is actually invalid syntax. You should use ArgumentMatchers only for parameters of mocked methods.
Also consider adding the MockitoAnnotations.initMocks(this); to your setUp method, when using the PowerMockRunner.

Why Shiro's SubjectCallable need invoke restore method?

SubjectCallable's call method:
public V call() throws Exception {
try {
threadState.bind();
return doCall(this.callable);
} finally {
threadState.restore();
}
}
1.bind method is necsssary, but restore is why?
public void bind() {
SecurityManager securityManager = this.securityManager;
if ( securityManager == null ) {
//try just in case the constructor didn't find one at the time:
securityManager = ThreadContext.getSecurityManager();
}
this.originalResources = ThreadContext.getResources();
ThreadContext.remove();
ThreadContext.bind(this.subject);
if (securityManager != null) {
ThreadContext.bind(securityManager);
}
}
public void restore() {
ThreadContext.remove();
if (!CollectionUtils.isEmpty(this.originalResources)) {
ThreadContext.setResources(this.originalResources);
}
}
2.originalResources is use to do ? each time enter the AbstractShiroFilter will create a new subject and invoke it's execute method, the originalResources seems useless.
General thread health. You need to clean up resource in case the thread is re-used (very common). And it would help with garbage collection too.
Do you ever go hiking? Leave no trace ;)

handling a specific exception type

I've defined two AfterThrowing advices to handle exceptions with the same pointcut.
#AfterThrowing(pointcut="...", throwing="ex")
public void method1(Exception ex) {}
#AfterThrowing(pointcut="...", throwing="ex")
public void method2(GatewayException ex) {}
Is there a way for me to prevent the generic method1 being executed if the exception is a GatewayException?
Any ideas greatly appreciated
C
It would be the easiest to check the instance of the exception inside the advice body and return early if it's of the more specific exception type:
#AfterThrowing(pointcut="...", throwing="ex")
public void method1(Exception ex) {
if (ex instanceof GatewayException) {
return;
}
// handle the more generic Exception case
}
#AfterThrowing(pointcut="...", throwing="ex")
public void method2(GatewayException ex) {
// handle the more specific GatewayException
}
I know you expected a solution based on some AspectJ language construct, but the thing is, there's no such construct.

How to create a custom exception and handle it in dart

I have written this code to test how custom exceptions are working in the dart.
I'm not getting the desired output could someone explain to me how to handle it??
void main()
{
try
{
throwException();
}
on customException
{
print("custom exception is been obtained");
}
}
throwException()
{
throw new customException('This is my first custom exception');
}
You can look at the Exception part of A Tour of the Dart Language.
The following code works as expected (custom exception has been obtained is displayed in console) :
class CustomException implements Exception {
String cause;
CustomException(this.cause);
}
void main() {
try {
throwException();
} on CustomException {
print("custom exception has been obtained");
}
}
throwException() {
throw new CustomException('This is my first custom exception');
}
You don't need an Exception class if you don't care about the type of Exception. Simply fire an exception like this:
throw ("This is my first general exception");
You can also create an abstract exception.
Inspiration taken from TimeoutException of async package (read the code on Dart API and Dart SDK).
abstract class IMoviesRepoException implements Exception {
const IMoviesRepoException([this.message]);
final String? message;
#override
String toString() {
String result = 'IMoviesRepoExceptionl';
if (message is String) return '$result: $message';
return result;
}
}
class TmdbMoviesRepoException extends IMoviesRepoException {
const TmdbMoviesRepoException([String? message]) : super(message);
}
Try this Simple Custom Exception Example for Beginners
class WithdrawException implements Exception{
String wdExpMsg()=> 'Oops! something went wrong';
}
void main() {
try {
withdrawAmt(400);
}
on WithdrawException{
WithdrawException we=WithdrawException();
print(we.wdExpMsg());
}
finally{
print('Withdraw Amount<500 is not allowed');
}
}
void withdrawAmt(int amt) {
if (amt <= 499) {
throw WithdrawException();
}else{
print('Collect Your Amount=$amt from ATM Machine...');
}
}

Entity Framework - DbUpdateException to a custom Exception

I am using Entity Framework and when a DbUpdateException is thrown from dbContext.SaveChanges() how do I create a custom exception and throw that instead?
Would I create a condition on each SQL constraint that can be thrown:
if (e.InnerException.InnerException.Message.Contains("UNIQUE KEY"))
{
throw new CustomException("message");
}
EDIT: That approach makes good sense to me. If you know your application/DB is going to have a specific error, and it will help you or your users to have a specific custom exception type that quickly identifies what would otherwise be a somewhat complex or specific scenario, then absolutely yes. It's good practice to use both the exception type and the exception message to make the error as clear as possible. My code below is an even simpler example than what you seem to drilling down into. Rather than letting other code end up with a null reference exception or some other consequence, I beat everything to the punch with throw new DatabaseDataNotFoundException("Cannot find ServerAppConfiguration value for {0}", key);.
Just make your own exception class that inherits from Exception, here's a custom exception I use for exactly that purpose:
public class DatabaseDataNotFoundException : Exception
{
public DatabaseDataNotFoundException() : base() { }
public DatabaseDataNotFoundException(string message) : base(message) { }
public DatabaseDataNotFoundException(string message, params object[] args)
: base(String.Format(CultureInfo.CurrentCulture, message, args)) { }
public DatabaseDataNotFoundException(string message, Exception inner)
: base(message, inner) { }
public DatabaseDataNotFoundException(string message, Exception inner, params object[] args)
: base(String.Format(CultureInfo.CurrentCulture, message, args), inner) { }
protected DatabaseDataNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
Then your code becomes:
if (e.InnerException.InnerException.Message.Contains("UNIQUE KEY"))
{
throw new DatabaseDataNotFoundException("message");
}