Kotlin doesn't have checked exceptions. Would it be bad practice to catch the class Exception in Kotlin code? In Java this would be a no go.
Are there other ways than relying on the api docs of the function you are calling to handle exceptions the right way?
fun beSave() {
try {
// some blackbox code
}
catch (e: Exception) {
// handler
}
}
Related
Why we need multiple "catch" blocks even though we can write one generic
exception?
Is that important to know all the exception types and their purposes to make a good piece of code?
I googled a lot but still have confusions in exception handling. Any good example?
Generic Exception:
try{
//some code
}
catch(Exception e){
//print e
}
//that's it.
Multiple catches
try{
//some code
}
catch(IOException e){
}
catch(SQLException e){
}
There are several advantages of using multiple exceptions:
General exceptions will not let you know the exact root cause of the issue especially if many steps/checks involved in a method implementation. Also, If the exception occurs due to various reasons, you need to throw the different types of exceptions from your caller method implementation.
Eg: You can throw custom exceptions.
Here is your service code:
public void Login(string username, string password)
{
if(string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
throw InvalidUserNameException();
}
if(!IsInternetAvaialable())
{
throw NoInternetAvailableException()
}
else
{
//Implement though your login process and if need use various custom exceptions or throw the exception if occurs.
}
}
public class InvalidUserNameException : Exception
{
public InvalidUserNameException()
{
}
public InvalidUserNameException(string message)
: base(message)
{
}
public InvalidUserNameException(string message, Exception inner)
: base(message, inner)
{
}
}
Caller Method:
try {
...
} catch(InvalidUserNameException e) {
// Show Alert Message here
} catch(NoInternetAvaibleException e) {
// Show Alert Message with specific reason
}
catch(Exception e) {
// Other Generic Exception goes here
}
Reference:
https://learn.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-user-defined-exceptions
1. Why we need multiple "catch" blocks even though we can write one generic exception?
Sometimes you might need to specify what causes the problem.
For example,
try {
...
} catch(IOException e) {
// Print "Error: we cannot open your file"
} catch(SQLException e) {
// Print: "Error: we cannot connect to the database"
}
With different errors, users can understand what went wrong easily.
If we go with
try {
...
} catch(Exception e) {
// Print "Error: " + e.
}
It's harder for the users to figure out what went wrong.
Also, we can send the users to different pages accordingly to the error if we use multiple catch-es.
2.Is that important to know all the exception types and their purposes to make a good piece of code?
Personally, I would go with important exceptions such as IO, DB, etc. that can cause serious trouble. For others, I would catch with general exception.
I'm using rxAndroid.
I've read many documents, but still not found the solution, and maybe I missed it,
so please give me a guide.
Here I created an observable that might throw an exception in subscribe method.
return Observable.create(new ObservableOnSubscribe<Project>() {
#Override
public void subscribe(#NonNull ObservableEmitter<Project> e) throws Exception {
e.onNext(projectRepository.readDetails(project.getId()));
e.onComplete();
}
});
I use repository pattern to get the project details,
but the problem is all of the repository methods might throw an exception,
projectRepository.readDetails(project.getId())
And I couldn't find anyway to handle the exception throwed in the method subscibe(), Observer's onError() will not get any notification of it.
Thanks.
When creating an observable manually, you have to catch any exception and pass them to the onError() manually:
return Observable.create(new ObservableOnSubscribe<Project>() {
#Override
public void subscribe(#NonNull ObservableEmitter<Project> e) throws Exception {
try {
e.onNext(projectRepository.readDetails(project.getId()));
e.onComplete();
}
catch (Exception ex) {
e.onError(ex);
}
}
});
Alternatively you should be able to use fromCallable() to avoid having to create the observable manually:
Observable.fromCallable(() -> projectRepository.readDetails(project.getId()));
This will signal onError() if the call should fail.
I have the following method:
public Object method(){
try
{
privatevoidmethod1();
privatevoidmethod2();
}
catch(Exception e)
{
Log.debug(e);
}
return object;
}
How do I force the exception so I can test the debug call?
Leaving aside how you'd test the debug call, you'd normally trigger an exception by providing suitable inputs such that an exception would be created/thrown. If that's not suitable, the alternative is to provide a substitute (mocked) component that has been configured/written to throw an exception e.g.
public MyClass(MyInjectedComponent component) {
this.component = component;
}
and you'd provide for your test an implementation of MyInjectedComponent that will throw an exception (for testing purposes). The approach of injecting components into other components is called dependency injection and worth investigating.
I'd normally use a mocking framework for this (e.g. Mockito or similar). However a trivial implementation of the above could be:
public class MyImplementationForTesting extends MyInjectedComponent {
public void method() throws Exception {
throw new Exception();
}
}
Is there any language that supports something like the below construct, or is there a good way to achieve this using the ubiquitous try-catch-finally?
try
{
} catch(Exception1 e)
{ .... }
catch(Exception2 e)
{ .... }
catch-finally
{
//Perform action, such as logging
}
finally
{
//This always occurs but I only want to log when an exception occurs.
}
I understand this depends on the particular language, but is there some such support in Java, C#, C++, PHP etc?
Put a "global" try/catch in your main program or high-level method. This catches all exceptions that are not caught elsewhere.
try
{
// Main method, or higher level method call
}
catch (Exception ex)
{
// Log exception here
}
Then, in your subordinate try/catch clauses, just handle your exceptions in the usual way, and then rethrow. The rethrown exception will bubble up to your main try/catch and be logged.
try
{
// Do your thing
}
catch(SomeException ex)
{
// Handle exception here
// rethrow exception to logging handler
throw;
}
I don't think so as the behaviour you describe can be easily modelled as:
boolean success = false;
try {
...
success = true;
} catch (Exception_1 e) {
...
}
...
} catch (Exception_N e) {
...
} finally {
if (success) {
// your "finally"
} else {
// your "catch-finally"
}
}
You can easily accomplish that in C#. A simple way would be to save the exception in your catch blocks, then in your finally block, log if the exception object is not null.
Exception ex;
try
{
}
catch (ExceptionType1 type1)
{
ex = type1;
}
catch (ExceptionType2 type2)
{
ex = type2;
}
finally
{
if (ex != null)
{
//Log
}
}
Visual Basic has a construct that can be used for this. This isn't really "finally" in the sense of [almost] never failing to execute, but it'll support the case when you only want to log the exceptions that you're handling, and you have access to the exception object within the shared code. You've also got the flexibility of having the shared code execute before or after the individual exception type code.
Try
...
Catch ex As Exception When TypeOf(ex) Is Type1 OrElse TypeOf(ex) Is Type2
...
If TypeOf(ex) Is Type1 Then
...
ElseIf TypeOf(ex) Is Type2 Then
...
End If
End Try
Something like this, as long as the language has throw with no parameters to rethrow a caught exception:
try
{
} catch(Everything) {
try {
throw;
} catch (Exception1 e) {
....
} catch (Exception2 e) {
....
} finally {
//Perform action, such as logging
}
} finally {
//This always occurs but I only want to log when an exception occurs.
}
That's if you want to log whenever an exception occurs - if you only want to log the ones you actually catch, then don't put the "Perform action" in a finally block, just put it after the end of the inner try-catch.
I am trying to implement jms to my grails application.
I have several JMS consumer in a spring based enviroment listining
on an ActiveMQ broker. I wrote a simple test commandline client which creates
messages and receives them in an request response manner.
Here is the snippet that sends a MapMessage in Spring JMS way.
This works for me as long I am in my spring world.
final String corrID = UUID.randomUUID().toString();
asyncJmsTemplate.send("test.RequestQ", new MessageCreator()
{
public Message createMessage(Session session) throws JMSException {
try {
MapMessage msg = session.createMapMessage();
msg.setStringProperty("json", mapper.writeValueAsString(List<of some objects>));
msg.setJMSCorrelationID(corrID);
msg.setJMSReplyTo(session.createQueue("test.ReplyQ"));
return msg;
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
});
BUT when I tried to implement this methods to my grails test app
I receive some METHOD_DEF exceptions. Sending simple TextMessages
via the jmsTemplate.convertAndSende(Queue, Message) provided by
the JMS Plugin works.
Can any one help me? Is this a common problem?
Cheers Hans
Not actually trying this out, I have to believe this is a syntax problem. What you're really doing with that anonymous class is passing a closure containing all the MessageCreator code into the constructor for the MessageCreator class. In Groovy, closures can be passed as the last argument to a function merely by placing it after the function name or the parenthesized first arguments.
SomeFunction( arg1, arg2) { some code }
is the same as
SomeFunction( arg1, arg2, { some code } )
What you really want is to convert the closure into an anonymous instance of a MessageCreator, which I believe you can accomplish by:
asyncJmsTemplate.send("test.RequestQ",
{ code in the anonymous block } as MessageCreator );
I found this on StackOverflow, actually, though it's a poorly created question. Read all the responses, and you should see something relevant: Best groovy closure idiom replacing java inner classes?
I have had the same problems and here is my working solution:
I have created a new class MyMessageCreator in the src folder which implements the origin JMS MessageCreator interface.
With this I can create a new MyMessageCreator object and can call the createMessage(Session session) function to generate a new message.
To get the session object I use the jmsTemplate.
public class MyMessageCreator implements MessageCreator {
#Override
public Message createMessage(Session session) throws JMSException {
return session.createMapMessage();
}
}
Here is the relevant groovy code:
Session session = jmsTemplate.getConnectionFactory().createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)
MapMessage msg = new MyMessageCreator().createMessage(session);
Hope this helps,
Mirko