Kotlin socket property getter should I check for exception? - android

I'm writing an Android bluetooth client application in Kotlin. Now I'm trying to get OutputStream from a connected socket.
When writing in Java, I have to check for IOException:
OutputStream stream;
try
{
stream = socket.getOutputStream();
}
catch(IOException e)
{ ... }
But in Kotlin, it seems that I can directly get the object through getters
val streamOut : OutputStream = socket.outputStream
The question is should I check for IOExecption as well? Or is the outputstream already set in the socket.connect() step?

Java is very strict about exceptions. Whenever you write a code that could throw an exception, you need to either catch it or mark your own method with throws. Kotlin does not require this, you are not enforced to catch exceptions, but that doesn't mean it will auto-magically handle errors for you or something. socket.outputStream may throw an exception, so you need to be prepared for such a situation. If you omit catch {} block, then in the case of an error, it will propagate through the call stack.

Related

How to handle different kinds of errors in Retrofit Rx onError without ugly instanceof

I would like to know your ways to handle different kinds of errors (like http exceptions, no internet connection exceptions etc) in retrofit Rx onError without using instanceof like it's proposed here: How to handle network errors in Retrofit 2 with RxJava or here: Handle errors in Retrofit 2 RX
In kotlin I will simply make some extension functions for each kind of throwable to do whatever I want.
But I am forced to use Java in the project. Any nice suggestions?
is the approach to build some kind of error handler like this:
public interface ErrorHandler {
void handleError(Exception e);
void handleError(HttpException e);
void handleError(NullPointerException npe);
}
good? I know it is not because every time i need to handle another specific error I am forced to change interface, so it is violation of Open Close Principle. But I can't figure out any solution .
cheers
Wojtek
The compiler determines which method to call, rather than the VM. So the class you've described won't solve the problem unless you check instanceof first and cast the paramter to the correct type. Otherwise you're going to get handleError(Exception e) every time.
But I wanted to create an answer not for that reason, but to argue that having only one error handler is actually preferable in many cases, not a liability. Oftentimes in java we end up in awful situations like this:
catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No such algorithm: RSA?", e);
}
catch (NoSuchProviderException e) {
throw new IllegalStateException("No such provider: " + ANDROID_KEYSTORE_ID, e);
}
catch (InvalidAlgorithmParameterException e) {
throw new IllegalStateException("Bug setting up encryption key for user credentials: ", e);
}
catch (KeyStoreException e) {
throw new IllegalStateException("Bug setting up encryption key for user credentials: ", e);
}
catch (IOException e) {
Log.w(TAG, "Exception setting up keystore for user creds. They won't be stored.", e);
}
catch (CertificateException e) {
Log.w(TAG, "Exception setting up keystore for user creds. They won't be stored.", e);
}
Having only one error handler gives us the ability to lump many types of exceptions together. You can see in this code, there are exceptions that should never be thrown, exceptions that can really only be the result of a bug in the code, and legitimate exceptional states that we need to handle. I find this messy, and would prefer to say:
if (e instanceof NoSuchAlgorithmException || e instanceof NoSuchProviderException) {
Log.wtf(TAG, "What the heck is this?", e);
throw new IllegalStateException("This is some kind of weird bug", e);
}
else if (e instanceof IOException || e instanceof CertificateException) {
// This can happen sometimes, track event in analytics and perhaps
// try some alternative means of credential storage.
}
else {
// At least here the app won't crash if some unexpected exception occurs,
// since we're trapping everything.
}
I don't think it's such a bad thing to be able to lump unexpected failures together and handle them in a more user friendly way than crashing the app. Even if it's just a bug, better to track it in your analytics framework behind the scenes than bomb the user out of the app. So many crashes in Android apps are actually completely recoverable, but we don't go around catching Throwable in every try/catch statement because it's a lot of extra code.
The proper OOP way to avoid chained ifs or catches is polymorphism. You can define several custom exception classes exposing common interface that is enough for a single handler to process.
Suppose you need to divide errors in two groups: recoverable and not recoverable. Then your base exception class (or interface) shall have abstract method isRecoverable() that you override in each subclass. Then there will be only one if in your handler: if (e.isRecoverable()) { ... } else { ... }.
The downside is that you have to wrap all standard exceptions into your custom ones at places where they are thrown (you have to catch them).
The right choice will greatly depend on your task, though.

Android NDK - try catch with NoMemoryError

I have block of code, which in Android NDK allocates huge ammounts of memory. Last what I need is to use try - catch block for possibility, there might be NoMemoryError. Do you know how to write it in native SDK?
I need to implement same functionality as this:
for(int i=1;i<50;i++){
try{
int[] mega =new int[i*1024*1024];//1MB
}catch (OutOfMemoryError e) {
usedMemory= (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/new Float(1048576.0);
usedText=usedMemory+" MB";
tw.setText(usedText);
break;
}
}
In your JNI function you can throw a java exception using the follow snippet. When compiling the native code make sure RTTI and exceptions are enabled.
try {
int *mega = new int[1024 * 1024];
} catch (std:: bad_alloc &e) {
jclass clazz = jenv->FindClass("java/lang/OutOfMemoryError");
jenv->ThrowNew(clazz, e.what());
}
In Java you can simply catch the OutOfMemoryError.
try {
// Make JNI call
} catch (OutOfMemoryError e) {
//handle error
}
Android is not very friendly to C++ exceptions (you must link with a special version of the C++ library provided by Android to have exceptions). Maybe you should use malloc() and check its return value to see if memory allocation was OK?
If you trigger an exception/error in your native code you should be able to catch it. However, I would assume that allocating a big chunk of unmanaged memory using malloc or similar will not trigger an error but kill you app the hard way. If you create the same big java array as in your java code instead, however, the java method you call to create the array will fail and create an exception. As exception handling in JNI is very different you have to check for exceptions in your native code manually using something like:
exc = (*env)->ExceptionOccurred(env);
if (exc) ...

A new error I never seen before in Android. Is there any Solution?

02-07 10:49:45.558: E/dalvikvm-gc(7184): Could not create 2617344-byte ashmem mark stack: Too many open files
While I was playing the game and after some time the game forced closed showing the above error in Log Cat. Is there any solution for this?? and what could be its cause??
The cause is that your code is not closing files and the system is running out of file handles. You should always use files using a coding pattern that ensures that all streams are closed when no longer needed. Here's a typical pattern:
InputStream is = null;
try {
is = new FileInputStream(myFile);
// read stuff from is
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.w(LOG_TAG, "Exception raised when closing file", e);
}
}
}
The outer try could also have a catch clause. The reason for the try/catch in the finally clause is to prevent an exception in closing the file from suppressing any exception raised in the outer try block.
Writing to files tends to be less of a problem because programmers usually take care to close the file to ensure that the data reaches the file. However, a similar pattern should be followed there: never let an exception prevent the closing of a file.

Android : BluetoothSocket and InputStream.available()

I want to check whether the BluetoothSocket is open for operation or not.....
Here is what I do:
First of all I get an InputStream from my BluetoothSocket, I want to perform some operation with that InputStream, if an IOException occurs my program can determine that socket is disconnected..... And after making sure that socket is connected I want to read some data from it.
For making sure I am calling available() which by default returns 0 or a number of bytes.... if return value is 0 my reading operation throws IOException.
Here are my questions.
Is available() blocking I/O call or an asynchronous one?
Return value >0 only when I give some input from my device while connecting, which will not always be the case. Am I doing any mistake allowing to read if there are 0 available bytes? How to avert this?
First u have to connect with a Bluetooth server. Use connect() to connect, this method will block until a connection is made or the connection fails (resulting in an exception). So make sure to run this on a separate thread.
public void run() {
try {
socket.connect();
InputStream in = socket.getInputStream();
//socket connected, inputStream can be used
//Bluetooth
} catch (IOException e) {
//Socket is refused connection with the server.
}
}

How to catch IOException Error in eclispe for Android?

I want to catch an IOException Error and want to show it in the form of toast for android application development. But when ever i apply catch(IOexception e), after try block it says to throws (throws IOException) with function name after which i am to catch error message.. Please Provide Some assistance....
May be you desire to 'throws' catched exception above the call stack, and next, catch and process all exception in one place (or 'layer') of code?)

Categories

Resources