简体   繁体   中英

Convert a String in Clob

I have a string "stringData" and I want to convert it in a Clob, can you help me?

I have tried:

Clob clob = new SerialClob(stringData.toCharArray());

but it gives error.

So the issue of Unhandled Exception isn't directly an issue with the .toCharArray() and SerialClob . Rather, the issue is that Checked Exceptions must either be caught or declared as part of the method.

So (Example 1):

try {
  ...
  Clob clob = new SerialClob(stringData.toCharArray());
  ...
}
catch (SQLException e) {
  // do handle better than this, however
  e.printStackTrace();
}

Or (Example 2):

/**
   @throws SQLException If there is an issue with creating the data, or 
                        inserting into the DB
*/
private void storeData(StringData stringData) throws SQLException
{
  ...
  Clob clob = new SerialClob(stringData.toCharArray());
  ...
 }

Of course, with the latter, some other method will need to catch the SQLException.

Essentially, an SQLException is a CheckedException. From the JLS 11.2

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method (§8.4.6) or constructor (§8.8.5) must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

So, either the SQLException must be caught (example 1), or added to the throws clause for the method (example 2).

The reason you received the compile time issue is found in JLS, 11.2.3 Exception Checking :

It is a compile-time error if a method or constructor body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the throws clause of the method or constructor.

There is also discussion in the accepted answer to this question about Checked vs. Unchecked Exceptions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM