I cannot catch the exception, instead a runtime error is thrown in the main method.
Any idea?
code below:
public class Test {
public static void main(String[] args) {
ArrayList myList = new ArrayList();
String[] myArray;
try{
while(true){
myList.add("My String");
}
}catch(RuntimeException re){
System.out.println("Caught a RuntimeException");
}catch(Exception re){
System.out.println("Caught a Exception");
}
System.out.println("Ready to use");
}
}
It will throw OutOfMemoryError which do not extend Exception. So you can not catch it by Exception.
public static void main(String[] args) {
ArrayList myList = new ArrayList();
try{
while(true){
myList.add("My String");
}
}catch(RuntimeException re){
System.out.println("Caught a RuntimeException");
}catch(Exception re){
System.out.println("Caught a Exception");
} catch (OutOfMemoryError e){
System.out.println("Out of memory");
}
System.out.println("Ready to use");
}
Related
ASP.NET Core Web Api Middleware Converts Custom Exception into Base Exception
I have created a custom exception class and use it throw an exception. The middleware catches it but throws base exception instead of custom exception. I am not able to understand why it does not catch custom exception.
Custom Exception
public class CustomException : Exception
{
public int HttpStatusCode { get; private set; }
public CustomException()
{
}
public CustomException(int httpStatusCode, string message):base(message)
{
HttpStatusCode = httpStatusCode;
}
}
Middleware
public class ExceptionMiddleware
{
public readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch(CustomException ex)
{
await HandleExceptionAsync(httpContext, ex);
}
catch(Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
int statusCode = (int)HttpStatusCode.InternalServerError;
if (ex is CustomException)
{
CustomException se = ex as CustomException;
statusCode = se.HttpStatusCode;
}
context.Response.ContentType = "application/json";
context.Response.StatusCode = statusCode;
return context.Response.WriteAsync(JsonConvert.SerializeObject(new InternalServerErrorResponse(ex.Message)));
}
}
Exception thrown
throw new CustomException(StatusCodes.Status422UnprocessableEntity, "User is already registered!");
When exception is thrown, middleware does not catch custom exception but base Exception. It always goes to the below code block
catch(Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
Please advise.
You can use exception filter to handle exceptions and easily manipulate response.
public class ExceptionFilter : IExceptionFilter
{
public ExceptionFilter(IHostingEnvironment env, ILogger<JsonExceptionFilter> logger)
{
_env = env;
_logger = logger;
}
public void OnException(ExceptionContext context)
{
var error = new ApiResponse();
var exceptionName = context.Exception.GetType().Name;
var message = context.Exception.Message;
if (_env.IsDevelopment())
{
error.Message = context.Exception.Message;
error.Detail = context.Exception.StackTrace;
}
else
{
//Prevent To Show Exception Messages On Production
error.Message = "Server Error Occured";
error.Detail = "Something wrong happened";
}
context.Result = new ObjectResult(error)
{
//Manipulate Status Code
StatusCode = 500
};
}
}
And register to Startup.cs
public void ConfigureServices(IServiceCollection services){
services.AddMvc(options =>
{
//Catch the exceptions
options.Filters.Add<ExceptionFilter>();
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
you have to tell your app to use this middleware in configure method in your startup class like this -
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger){
app.ExceptionMiddleware();
}
I want to make a JsonObjectRequest using POST method with volley library so that i can save my data on the server.
For the same, i've an API of jsonObject as follows:
{"settings":{"notification":30,"time":4}}
The java code for the same is as follows ;
public void sendrequest(String urlset)
{
RequestQueue requestQueue1=Volley.newRequestQueue(this);
JSONObject json=new JSONObject();
JsonObjectRequest jsonObjectRequest1=new JsonObjectRequest(Request.Method.POST, urlset, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//code for getting some response from the method
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//code in order to check the error
}
});
}
How can this be done so that I am able to post my data on the server using the above code (for reference).
Thanks in advance.
After a few attempts i tried doing this:
public void sendrequest(String urlset)
{
RequestQueue requestQueue1=Volley.newRequestQueue(this);
String a,b;
SharedPreferences sharedPreferences1=getSharedPreferences("MyPreferences",MODE_PRIVATE);
a=sharedPreferences1.getString("list_preference_1","");
b=sharedPreferences1.getString("list_preference_2","");
//a=sharedPreferences1.getInt("list_preference_1", 1);
//b=sharedPreferences1.getInt("list_preference_2", 1);
JSONObject json=new JSONObject();
try {
//JSONObject ob=json.getJSONObject("settings");
json.put("notification",Integer.parseInt(a));
json.put("time",Integer.parseInt(b));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Error 1", Toast.LENGTH_SHORT).show();
}
JSONObject jsonfinal=new JSONObject();
try {
jsonfinal.put("settings",json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Error 2", Toast.LENGTH_SHORT).show();
}
JsonObjectRequest jsonObjectRequest1=new JsonObjectRequest(Request.Method.POST, urlset, jsonfinal, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(SettingsActivity.this, "Changes made to server", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SettingsActivity.this, "Check internet connectivity", Toast.LENGTH_SHORT).show();
}
});
requestQueue1.add(jsonObjectRequest1);
}
But now my application is now crashing. Can someone help me out with this?
This is the easiest example of a complex issue. I haven't found the example of this problem anywhere in the entire internet. I'm validating the input in a validationMethod that return Boolean. Now, I need to use this method in calling class (run the flow if return is true, catch exception if return is false).
public class StringUtil{
public static boolean validateNumInput(String UserInput)
{
if(UserInput.matches("[0-9]+")){
return true;
} return false;
}
}
public class Main{
public static void main(String[] args){
String a="012*+";
try{
if(StringUtil.validateNumInput(a)){
System.out.println(StringUtil.validateNumInput(a));
}
}catch(Exception e){
System.out.println("Big problem");
}
}
}
According to the documentation, you can filter catch clauses with a Boolean predicate. So, your validation method would need to throw an exception which you could filter for in your catch clause. But if you're doing that, you might as well roll your own custom exception and not have to deal with the Boolean at all. The other alternative is, in your calling code, treat the return code as a return code and throw your own exception.
Option 1:
public class StringUtil{
public static boolean validateNumInput(String UserInput)
{
if(UserInput.matches("[0-9]+")){
return true;
}
throw new Exception ("Validation failed!");
}
}
public class Main{
public static void main(String[] args){
String a="012*+";
try{
if(StringUtil.validateNumInput(a)){
System.out.println(StringUtil.validateNumInput(a));
}
}catch(Exception e) when (e.Message == "Validation failed!") {
System.out.println("Big problem");
}
}
}
Option 2:
public class Main{
public static void main(String[] args){
String a="012*+";
try{
if(StringUtil.validateNumInput(a)){
System.out.println(StringUtil.validateNumInput(a));
} else {
throw new Exception ();
}
}catch(Exception e) {
System.out.println("Big problem");
}
}
}
public class MainActivity extends AppCompatActivity {
private AutoCompleteTextView autoCompleteTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
new HttpGetTask().execute("http://192.168.0.107/abc/translator.php");
}
public class HttpGetTask extends AsyncTask<String, String, List<TranslatorModel>> {
#Override
protected List<TranslatorModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<TranslatorModel> translatorModelList = new ArrayList<>();
for(int i= 0; i<parentArray.length();i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
TranslatorModel translatorModel = new TranslatorModel();
translatorModel.setEnglish(finalObject.getString("englishSentence"));
translatorModelList.add(translatorModel);
}
return translatorModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<TranslatorModel> data) {
super.onPostExecute(data);
}
}
}
englishSentence is a string json object . setter and getter methods are defined in a TranslatorModel class. i want to display englishSentence values in my autocompleteTextView
Problem:
Which code will be used for displaying data in autocompletetextview ?
Where to add array adaptar class and which code will work ?
Which code will be used onPostExecute Method ?
add ArrayAdapter inside onPostExecute method
#Override
protected void onPostExecute(List<TranslatorModel> data) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,data);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setThreshold(1);
super.onPostExecute(data);
}
My application uses Java class RandomAccessFile to read/write bytes to a file on SD card randomly by means of realization of SeekableByteChannel interface. Now I need rewrite it for Android 5.0 with new Lollipop API.
I have found the only way to read:
InputStream inputStream = getContentResolver().openInputStream(uri);
and write:
ParcelFileDescriptor pfd = getActivity().getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
from/to a file in new API.
I would like to have an ability to set channel in some random position and read/write bytes to that position. Is it possible to do that in new SDK 21? Does new SDK imply this way obtaining of channels:
FieInputChannel fieInputChannel = fileInputStream.getChannel();
FieOutputChannel fieOutputChannel = fileOutputStream.getChannel();
or some other approach?
It seems the only way to get a random read/write access to a file on SD card for SDK 21 (Lollipop) is as follows:
import android.content.Context;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import com.jetico.bestcrypt.FileManagerApplication;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class SecondaryCardChannel {//By analogy with the java.nio.channels.SeekableByteChannel
private FileChannel fileChannel;
private ParcelFileDescriptor pfd;
private boolean isInputChannel;
private long position;
public SecondaryCardChannel(Uri treeUri, Context context) {
try {
pfd = context.getContentResolver().openFileDescriptor(treeUri, "rw");
FileInputStream fis = new FileInputStream(pfd.getFileDescriptor());
fileChannel = fis.getChannel();
isInputChannel = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int read(ByteBuffer buffer) {
if (!isInputChannel) {
try {
fileChannel.close();
FileInputStream fis = new FileInputStream(pfd.getFileDescriptor());
fileChannel = fis.getChannel();
isInputChannel = true;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fileChannel.position(position);
int bytesRead = fileChannel.read(buffer);
position = fileChannel.position();
return bytesRead;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public int write(ByteBuffer buffer) {
if (isInputChannel) {
try {
fileChannel.close();
FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
fileChannel = fos.getChannel();
isInputChannel = false;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fileChannel.position(position);
int bytesWrite = fileChannel.write(buffer);
position = fileChannel.position();
return bytesWrite;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public long position() throws IOException {
return position;
}
public SecondaryCardChannel position(long newPosition) throws IOException {
position = newPosition;
return this;
}
public long size() throws IOException {
return fileChannel.size();
}
public SecondaryCardChannel truncate(long size) throws IOException {
fileChannel.truncate(size);
return this;
}
}
EDIT 15/03/2017:
Little bit optimized version looks like
import android.content.Context;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class SecondaryCardChannel {
private ParcelFileDescriptor pfdInput, pfdOutput;
private FileInputStream fis;
private FileOutputStream fos;
private long position;
public SecondaryCardChannel(Uri treeUri, Context context) {
try {
pfdInput = context.getContentResolver().openFileDescriptor(treeUri, "r");
pfdOutput = context.getContentResolver().openFileDescriptor(treeUri, "rw");
fis = new FileInputStream(pfdInput.getFileDescriptor());
fos = new FileOutputStream(pfdOutput.getFileDescriptor());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int read(ByteBuffer buffer) {
try {
FileChannel fch = fis.getChannel();
fch.position(position);
int bytesRead = fch.read(buffer);
position = fch.position();
return bytesRead;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public int write(ByteBuffer buffer) {
try {
FileChannel fch = fos.getChannel();
fch.position(position);
int bytesWrite = fch.write(buffer);
position = fch.position();
return bytesWrite;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public long position() throws IOException {
return position;
}
public SecondaryCardChannel position(long newPosition) throws IOException {
position = newPosition;
return this;
}
public long size() throws IOException {
return fis.getChannel().size();
}
public void force(boolean metadata) throws IOException {
fos.getChannel().force(metadata);
pfdOutput.getFileDescriptor().sync();
}
public long truncate(long size) throws Exception {
FileChannel fch = fos.getChannel();
try {
fch.truncate(size);
return fch.size();
} catch (Exception e){ // Attention! Truncate is broken on removable SD card of Android 5.0
e.printStackTrace();
return -1;
}
}
public void close() throws IOException {
FileChannel fch = fos.getChannel();
fch.close();
fos.close();
fis.close();
pfdInput.close();
pfdOutput.close();
}
}