我已经用Java编写了一段时间了.但有时候,我不明白何时应该抛出异常,何时应该捕获异常.我正在开发一个有很多方法的项目.层次结构是这样的 -
Method A will call Method B and Method B will call some Method C and Method C will call Method D and Method E.
Run Code Online (Sandbox Code Playgroud)
所以我目前正在做的是 - 我在所有方法中抛出异常并在方法A中捕获它然后记录为错误.
但我不确定这是否是正确的方法呢?或者我应该开始捕获所有方法中的异常.所以这就是为什么这种混乱开始于我 - 我应该何时捕获异常与何时应该抛出异常.我知道这是一个愚蠢的问题,但不知怎的,我正在努力理解这个主要概念.
有人能给我一个详细的例子,When to catch the Exception vs When to throw the Exceptions以便我的概念得到澄清吗?在我的情况下,我应该继续抛出异常然后在主调用方法A中捕获它吗?
我试图从Python解析JSON.我最近开始使用Python,所以我按照一些stackoverflow教程如何使用Python解析JSON,我想出了下面的代码 -
#!/usr/bin/python
import json
j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
print j['script']
Run Code Online (Sandbox Code Playgroud)
但每当我运行上面的代码,我总是得到这个错误 -
Traceback (most recent call last):
File "json.py", line 2, in <module>
import json
File "/cygdrive/c/ZookPython/json.py", line 4, in <module>
j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
AttributeError: 'module' object has no attribute 'loads'
Run Code Online (Sandbox Code Playgroud)
有什么想法,我在这里做错了什么?我在windows中运行cygwin,只是在运行我的python程序.我使用的是Python 2.7.3
是否还有更好,更有效的解析JSON的方法?
更新: -
如果我删除单引号,下面的代码不起作用,因为我从其他方法获取JSON字符串 -
#!/usr/bin/python
import json
jsonStr = {"script":"#!/bin/bash echo Hello World"}
j = json.loads(jsonStr)
shell_script = j['script']
print shell_script
Run Code Online (Sandbox Code Playgroud)
所以在反序列化如何确定之前,它还有单引号?
这是我得到的错误 -
Traceback (most recent call last):
File …Run Code Online (Sandbox Code Playgroud) 我有一个List,我需要使用GSON转换为JSON对象.我的JSON对象中包含JSON数组.
public class DataResponse {
private List<ClientResponse> apps;
// getters and setters
public static class ClientResponse {
private double mean;
private double deviation;
private int code;
private String pack;
private int version;
// getters and setters
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我的代码,我需要将我的List转换为JSON对象,其中包含JSON数组 -
public void marshal(Object response) {
List<DataResponse.ClientResponse> clientResponse = ((DataResponse) response).getClientResponse();
// now how do I convert clientResponse list to JSON Object which has JSON Array in it using GSON?
// String jsonObject = ??
}
Run Code Online (Sandbox Code Playgroud)
截至目前,我在List中只有两个项目 - 所以我需要这样的JSON对象 -
{ …Run Code Online (Sandbox Code Playgroud) 我现在很困惑为什么我无法解析这个JSON字符串.类似的代码在其他JSON字符串上工作正常但不在这一个 - 我试图解析JSON字符串并从JSON中提取脚本.
以下是我的代码.
for step in steps:
step_path = '/example/v1' +'/'+step
data, stat = zk.get(step_path)
jsonStr = data.decode("utf-8")
print(jsonStr)
j = json.loads(json.dumps(jsonStr))
print(j)
shell_script = j['script']
print(shell_script)
Run Code Online (Sandbox Code Playgroud)
所以第一个print(jsonStr)会打印出这样的东西 -
{"script":"#!/bin/bash\necho Hello world1\n"}
Run Code Online (Sandbox Code Playgroud)
第二个print(j)会打印出这样的东西 -
{"script":"#!/bin/bash\necho Hello world1\n"}
Run Code Online (Sandbox Code Playgroud)
然后第三次打印没有打印出来,它给出了这个错误 -
Traceback (most recent call last):
File "test5.py", line 33, in <module>
shell_script = j['script']
TypeError: string indices must be integers
Run Code Online (Sandbox Code Playgroud)
所以我想知道我在这里做错了什么?
我使用相同的上面的代码来解析JSON,它工作正常..
以下是我的界面 -
public interface IDBClient {
public String read(ClientInput input);
}
Run Code Online (Sandbox Code Playgroud)
这是我的接口实现 -
public class DatabaseClient implements IDBClient {
@Override
public String read(ClientInput input) {
}
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个工厂得到这样的实例DatabaseClient-
IDBClient client = DatabaseClientFactory.getInstance();
....
Run Code Online (Sandbox Code Playgroud)
现在我需要调用readmy DatabaseClient接受ClientInput参数的方法,下面是相同的类.这个课不是我写的,所以这就是我对此有疑问的原因,我非常确定这是错误的做法.
public final class ClientInput {
private Long userid;
private Long clientid;
private Long timeout_ms = 20L;
private boolean debug;
private Map<String, String> parameterMap;
public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) {
this.userid = …Run Code Online (Sandbox Code Playgroud) 我正在开发一个项目,我需要对我正在运行的服务器进行HTTP URL调用,该服务器Restful Service将响应作为JSON字符串返回.
下面是我使用的主要代码future和callables-
public class TimeoutThreadExample {
private ExecutorService executor = Executors.newFixedThreadPool(10);
public String getData() {
Future<String> future = executor.submit(new Task());
String response = null;
try {
response = future.get(100, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我的Task类实现Callable接口并使用RestTemplate...
class Task implements Callable<String> {
private RestTemplate restTemplate = new RestTemplate();
public …Run Code Online (Sandbox Code Playgroud) 我正在使用Hadoop,我需要找到我的Hadoop文件系统中的~100个文件中的哪一个包含某个字符串.
我可以看到我想要搜索的文件,如下所示:
bash-3.00$ hadoop fs -ls /apps/mdhi-technology/b_dps/real-time
Run Code Online (Sandbox Code Playgroud)
..which返回几个这样的条目:
-rw-r--r-- 3 b_dps mdhi-technology 1073741824 2012-07-18 22:50 /apps/mdhi-technology/b_dps/HADOOP_consolidated_RT_v1x0_20120716_aa
-rw-r--r-- 3 b_dps mdhi-technology 1073741824 2012-07-18 22:50 /apps/mdhi-technology/b_dps/HADOOP_consolidated_RT_v1x0_20120716_ab
Run Code Online (Sandbox Code Playgroud)
如何找到哪些包含字符串bcd4bc3e1380a56108f486a4fffbc8dc?一旦我知道,我可以手动编辑它们.
我在CQL下面的表格 -
create table test (
employee_id text,
employee_name text,
value text,
last_modified_date timeuuid,
primary key (employee_id)
);
Run Code Online (Sandbox Code Playgroud)
我在上表中插入了几条记录,我将在实际用例场景中插入这些记录 -
insert into test (employee_id, employee_name, value, last_modified_date) values ('1', 'e27', 'some_value', now());
insert into test (employee_id, employee_name, value, last_modified_date) values ('2', 'e27', 'some_new_value', now());
insert into test (employee_id, employee_name, value, last_modified_date) values ('3', 'e27', 'some_again_value', now());
insert into test (employee_id, employee_name, value, last_modified_date) values ('4', 'e28', 'some_values', now());
insert into test (employee_id, employee_name, value, last_modified_date) values ('5', 'e28', 'some_new_values', now()); …Run Code Online (Sandbox Code Playgroud) 我想生成一些随机IP地址.但是evertime这个generateIPAddress函数返回0.0.0.0字符串作为ipAddress.但它应该每次都返回一些除0.0.0.0以外的随机ipAddress.任何建议为什么会发生?
private void callingGeoService() {
int p1 = 255;
int p2 = 0;
int p3 = 0;
int inc = 5;
String ipAddress = generateIPAddress(p1, p2, p3);
p3 += inc;
if (p3 > 255) {
p3 = 0;
p2 += inc;
if (p2 > 255) {
p2 = 0;
p1--;
if (p1 <= 0) {
p1 = 0;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是generateIPAddress方法
private String generateIPAddress(int p1, int p2, int p3) {
StringBuilder sb = null;
int b1 = (p1 …Run Code Online (Sandbox Code Playgroud) 我在我的代码中使用Java Callable Future.下面是我使用未来和callables的主要代码 -
public class TimeoutThread {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(5);
Future<String> future = executor.submit(new Task());
try {
System.out.println("Started..");
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我的Task类,它实现了Callable接口,我需要根据我们拥有的主机名生成URL,然后使用调用SERVERS RestTemplate.如果第一个主机名中有任何异常,那么我将为另一个主机名生成URL,我将尝试拨打电话.
class Task implements Callable<String> {
private static RestTemplate restTemplate = new RestTemplate();
@Override
public String call() throws Exception {
//.. some code
for(String hostname : hostnames) {
if(hostname == null) {
continue;
}
try …Run Code Online (Sandbox Code Playgroud)