WiMa WiMa - 1 year ago 222
Java Question

How to fix Unhandled exception: java.sql.SQLException for throw sqle

As a part of my app(API 11) I need to provide a predefined database and I found a tutorial online. So here is the java code but I get an error "Unhandled exception: java.sql.SQLException" on (throw sqle;).

Any ideas how to fix?

Thanks for your time

package com.wima.twomatrixlibrarisampletest;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.sql.SQLException;

public class Main210Activity extends AppCompatActivity {

Cursor c = null;

protected void onCreate(Bundle savedInstanceState) {

((Button) findViewById(R.id.button01)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DatabaseHelper myDbHelper = new DatabaseHelper(Main210Activity.this);
try {
} catch (IOException ioe) {
throw new Error ("Unable to create database");
try {
} catch (SQLException sqle) {
throw sqle;
Toast.makeText (Main210Activity.this, "Plz Work!", Toast.LENGTH_LONG).show();
c = myDbHelper.query("EMP_TABLE", null, null, null, null, null, null);
if(c.moveToFirst()) {
do {
Toast.makeText(Main210Activity.this, "_id: " + c.getString(0) + "\n" +
"E_Flange: " + c.getString(1) + "\n" +
"E_Web: " + c.getString(2) + "\n" +
"E_Ratio: " + c.getString(3), Toast.LENGTH_SHORT).show();
}while (c.moveToNext());

Answer Source

Exceptions come in two types Handled and Runtime.

Handled exceptions Must be caught(Try Catch) or thrown (throws)

Example SQLException, IOExeption

Runtime Exceptions can be caught but they do not need to be declared as thrown.

example: OutOfMemoryException, IndexOutOfBoundsException.

SQLException is a Handled Exception so as the other answer declared you either have to surround your call in a try catch block to handle the exception or declare

public void onClick(View v) throws SqlException {

In your case, you are catching it then rethrowing it, this means that the method has to declare it as thrown which sort of defeats the object of the try catch, usually unless you need to throw it up, you should log the error then silently continue, in your case you are declaring throw e; which is just literally throwing the problem up a level, and to do that you need to as previously mentioned - declare that the method throws it The throw new Error() is a runtime exception so it does not need to be declared, So if you don't want to have to declare it thrown you could try something like

throw new Error(sqle.getMessage());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download