java运行报错,下面是java代码运行

审查Java代码的十一种常见错误
发表于 15:09|
来源中国IT实验室|
作者chenqiuge1984
摘要:代码审查是消灭Bug最重要的方法之一,这些审查在大多数时候都特别奏效。由于代码审查本身所针对的对象,就是俯瞰整个代码在测试过程中的问题和Bug。并且,代码审查对消除一些特
代码审查是消灭Bug最重要的方法之一,这些审查在大多数时候都特别奏效。由于代码审查本身所针对的对象,就是俯瞰整个代码在测试过程中的问题和Bug。并且,代码审查对消除一些特别细节的错误大有裨益,尤其是那些能够容易在阅读代码的时候发现的错误,这些错误往往不容易通过机器上的测试识别出来。本文就常见的Java代码中容易出现的问题提出一些建设性建议,以便您在审查代码的过程中注意到这些常见的细节性错误。
通常给别人的工作挑错要比找自己的错容易些。别样视角的存在也解释了为什么作者需要编辑,而运动员需要教练的原因。不仅不应当拒绝别人的批评,我们应该欢迎别人来发现并指出我们的编程工作中的不足之处,我们会受益匪浅的。
正规的代码审查(code inspection)是提高代码质量的最强大的技术之一,代码审查&由同事们寻找代码中的错误&所发现的错误与在测试中所发现的错误不同,因此两者的关系是互补的,而非竞争的。
如果审查者能够有意识地寻找特定的错误,而不是靠漫无目的的浏览代码来发现错误,那么代码审查的效果会事半功倍。在这篇文章中,我列出了11个Java编程中常见的错误。你可以把这些错误添加到你的代码审查的检查列表(checklist)中,这样在经过代码审查后,你可以确信你的代码中不再存在这类错误了。
一、常见错误1# :多次拷贝字符串
测试所不能发现的一个错误是生成不可变(immutable)对象的多份拷贝。不可变对象是不可改变的,因此不需要拷贝它。最常用的不可变对象是String。
如果你必须改变一个String对象的内容,你应该使用StringBuffer。下面的代码会正常工作:
String s = new String (&Text here&);
但是,这段代码性能差,而且没有必要这么复杂。你还可以用以下的方式来重写上面的代码:
String temp = &Text here&;
String s = new String (temp);
但是这段代码包含额外的String,并非完全必要。更好的代码为:
String s = &Text here&;
二、常见错误2#: 没有克隆(clone)返回的对象
封装(encapsulation)是面向对象编程的重要概念。不幸的是,Java为不小心打破封装提供了方便&&Java允许返回私有数据的引用(reference)。下面的代码揭示了这一点:
import java.awt.D
public class Example{
private Dimension d = new Dimension (0, 0);
public Example (){ }
public synchronized void setValues (int height,int width) throws IllegalArgumentException{
if (height & 0 || width & 0)
throw new IllegalArgumentException();
d.height =
public synchronized Dimension getValues(){
Example类保证了它所存储的height和width值永远非负数,试图使用setValues()方法来设置负值会触发异常。不幸的是,由于getValues()返回d的引用,而不是d的拷贝,你可以编写如下的破坏性代码:
Example ex = new Example();
Dimension d = ex.getValues();
d.height = -5;
d.width = -10;
现在,Example对象拥有负值了!如果getValues() 的调用者永远也不设置返回的Dimension对象的width 和height值,那么仅凭测试是不可能检测到这类的错误。
不幸的是,随着时间的推移,客户代码可能会改变返回的Dimension对象的值,这个时候,追寻错误的根源是件枯燥且费时的事情,尤其是在多线程环境中。
更好的方式是让getValues()返回拷贝:
public synchronized Dimension getValues(){
return new Dimension (d.x, d.y);
现在,Example对象的内部状态就安全了。调用者可以根据需要改变它所得到的拷贝的状态,但是要修改Example对象的内部状态,必须通过setValues()才可以。
三、常见错误3#:不必要的克隆
我们现在知道了get方法应该返回内部数据对象的拷贝,而不是引用。但是,事情没有绝对:
public class Example{
private Integer i = new Integer (0);
public Example (){ }
public synchronized void setValues (int x) throws IllegalArgumentException{
if (x & 0)
throw new IllegalArgumentException();
i = new Integer (x);
public synchronized Integer getValue(){
return new Integer (i.intValue());
这段代码是安全的,但是就象在错误1#那样,又作了多余的工作。Integer对象,就象String对象那样,一旦被创建就是不可变的。因此,返回内部Integer对象,而不是它的拷贝,也是安全的。
方法getValue()应该被写为:
public synchronized Integer getValue(){
Java程序比C++程序包含更多的不可变对象。JDK 所提供的若干不可变类包括:
& Character
& 大部分的Exception的子类
四、常见错误4# :自编代码来拷贝数组
Java允许你克隆数组,但是开发者通常会错误地编写如下的代码,问题在于如下的循环用三行做的事情,如果采用Object的clone方法用一行就可以完成:
public class Example{
private int[]
public void saveCopy (int[] data){
copy = new int[data.length];
for (int i = 0; i & copy. ++i)
copy[i] = data[i];
这段代码是正确的,但却不必要地复杂。saveCopy()的一个更好的实现是:
void saveCopy (int[] data){
copy = (int[])data.clone();
}catch (CloneNotSupportedException e){
如果你经常克隆数组,编写如下的一个工具方法会是个好主意:
static int[] cloneArray (int[] data){
return(int[])data.clone();
}catch(CloneNotSupportedException e){
这样的话,我们的saveCopy看起来就更简洁了:
void saveCopy (int[] data){
copy = cloneArray ( data);
五、常见错误5#:拷贝错误的数据
有时候程序员知道必须返回一个拷贝,但是却不小心拷贝了错误的数据。由于仅仅做了部分的数据拷贝工作,下面的代码与程序员的意图有偏差:
import java.awt.D
public class Example{
static final public int TOTAL_VALUES = 10;
private Dimension[] d = new Dimension[TOTAL_VALUES];
public Example (){ }
public synchronized void setValues (int index, int height, int width) throws IllegalArgumentException{
if (height & 0 || width & 0)
throw new IllegalArgumentException();
if (d[index] == null)
d[index] = new Dimension();
d[index].height =
d[index].width =
public synchronized Dimension[] getValues()
throws CloneNotSupportedException{
return (Dimension[])d.clone();
这儿的问题在于getValues()方法仅仅克隆了数组,而没有克隆数组中包含的Dimension对象,因此,虽然调用者无法改变内部的数组使其元素指向不同的Dimension对象,但是调用者却可以改变内部的数组元素(也就是Dimension对象)的内容。方法getValues()的更好版本为:
public synchronized Dimension[] getValues() throws CloneNotSupportedException{
Dimension[] copy = (Dimension[])d.clone();
for (int i = 0; i & copy. ++i){
if (d != null)
copy[i] = new Dimension (d[i].height, d[i].width);
在克隆原子类型数据的多维数组的时候,也会犯类似的错误。原子类型包括int,float等。简单的克隆int型的一维数组是正确的,如下所示:
public void store (int[] data) throws CloneNotSupportedException{
this.data = (int[])data.clone();
拷贝int型的二维数组更复杂些。Java没有int型的二维数组,因此一个int型的二维数组实际上是一个这样的一维数组:它的类型为int[]。简单的克隆int[][]型的数组会犯与上面例子中getValues()方法第一版本同样的错误,因此应该避免这么做。下面的例子演示了在克隆int型二维数组时错误的和正确的做法:
public void wrongStore (int[][] data) throws CloneNotSupportedException{
this.data = (int[][])data.clone();
public void rightStore (int[][] data){
this.data = (int[][])data.clone();
for (int i = 0; i & data. ++i){
if (data != null)
this.data[i] = (int[])data[i].clone();
六、常见错误6#:检查new 操作的结果是否为null
Java编程新手有时候会检查new操作的结果是否为null。可能的检查代码为:
Integer i = new Integer (400);
if (i == null)
throw new NullPointerException();
检查当然没什么错误,但却不必要,if和throw这两行代码完全是浪费,他们的唯一功用是让整个程序更臃肿,运行更慢。
C/C++程序员在开始写java程序的时候常常会这么做,这是由于检查C中malloc()的返回结果是必要的,不这样做就可能产生错误。检查C++中new操作的结果可能是一个好的编程行为,这依赖于异常是否被使能(许多编译器允许异常被禁止,在这种情况下new操作失败就会返回null)。在java 中,new 操作不允许返回null,如果真的返回null,很可能是虚拟机崩溃了,这时候即便检查返回结果也无济于事。
七、常见错误7#:用== 替代.equals
在Java中,有两种方式检查两个数据是否相等:通过使用==操作符,或者使用所有对象都实现的.equals方法。原子类型(int, flosat, char 等)不是对象,因此他们只能使用==操作符,如下所示:
int x = 4;
int y = 5;
if (x == y)
System.out.println (&Hi&);
if (x.equals (y))
System.out.println (&Hi&);
对象更复杂些,==操作符检查两个引用是否指向同一个对象,而equals方法则实现更专门的相等性检查。
更显得混乱的是由java.lang.Object 所提供的缺省的equals方法的实现使用==来简单的判断被比较的两个对象是否为同一个。
许多类覆盖了缺省的equals方法以便更有用些,比如String类,它的equals方法检查两个String对象是否包含同样的字符串,而Integer的equals方法检查所包含的int值是否相等。
大部分时候,在检查两个对象是否相等的时候你应该使用equals方法,而对于原子类型的数据,你用该使用==操作符。
八、常见错误8#: 混淆原子操作和非原子操作
Java保证读和写32位数或者更小的值是原子操作,也就是说可以在一步完成,因而不可能被打断,因此这样的读和写不需要同步。以下的代码是线程安全(thread safe)的:
public class Example{
private int
public void set (int x){
this.value =
不过,这个保证仅限于读和写,下面的代码不是线程安全的:
public void increment (){
在测试的时候,你可能不会捕获到这个错误。首先,测试与线程有关的错误是很难的,而且很耗时间。其次,在有些机器上,这些代码可能会被翻译成一条指令,因此工作正常,只有当在其它的虚拟机上测试的时候这个错误才可能显现。因此最好在开始的时候就正确地同步代码:
public synchronized void increment (){
九、常见错误9#:在catch 块中作清除工作
一段在catch块中作清除工作的代码如下所示:
OutputStream os = null;
os = new OutputStream ();
os.close();
}catch (Exception e){
if (os != null)
os.close();
尽管这段代码在几个方面都是有问题的,但是在测试中很容易漏掉这个错误。下面列出了这段代码所存在的三个问题:
1. 语句os.close()在两处出现,多此一举,而且会带来维护方面的麻烦。
2. 上面的代码仅仅处理了Exception,而没有涉及到Error。但是当try块运行出现了Error,流也应该被关闭。
3. close()可能会抛出异常。
上面代码的一个更优版本为:
OutputStream os = null;
os = new OutputStream ();
if (os != null)
os.close();
这个版本消除了上面所提到的两个问题:代码不再重复,Error也可以被正确处理了。但是没有好的方法来处理第三个问题,也许最好的方法是把close()语句单独放在一个try/catch块中。
十、常见错误10#: 增加不必要的catch 块
一些开发者听到try/catch块这个名字后,就会想当然的以为所有的try块必须要有与之匹配的catch块。
C++程序员尤其是会这样想,因为在C++中不存在finally块的概念,而且try块存在的唯一理由只不过是为了与catch块相配对。
增加不必要的catch块的代码就象下面的样子,捕获到的异常又立即被抛出:
}catch(Exception e){
不必要的catch块被删除后,上面的代码就缩短为:
十一、常见错误11#;没有正确实现equals,hashCode,或者clone 等方法
方法equals,hashCode,和clone 由java.lang.Object提供的缺省实现是正确的。不幸地是,这些缺省实现在大部分时候毫无用处,因此许多类覆盖其中的若干个方法以提供更有用的功能。但是,问题又来了,当继承一个覆盖了若干个这些方法的父类的时候,子类通常也需要覆盖这些方法。在进行代码审查时,应该确保如果父类实现了equals,hashCode,或者clone等方法,那么子类也必须正确。正确的实现equals,hashCode,和clone需要一些技巧。
我在代码审查的时候至少遇到过一次这些错误,我自己也犯过其中的几个错误。好消息是只要你知道你在找什么错误,那么代码审查就很容易管理,错误也很容易被发现和修改。即便你找不到时间来进行正规的代码审查,以自审的方式把这些错误从你的代码中根除会大大节省你的调试时间。花时间在代码审查上是值得的。
原文链接:
推荐阅读相关主题:
网友评论有(0)
CSDN官方微信
扫描二维码,向CSDN吐槽
微信号:CSDNnews
相关热门文章Java基础试题及其答案_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
Java基础试题及其答案
阅读已结束,下载文档到电脑
想免费下载更多文档?
定制HR最喜欢的简历
下载文档到电脑,方便使用
还剩8页未读,继续阅读
定制HR最喜欢的简历
你可能喜欢java抛出异常后代码继续执行的情况
java抛出异常后代码继续执行的情况
java抛出异常后下面的代码是否还会执行?例如下面情况
public void add(int index, E element){
if(size &= elements.length) {
throw new RuntimeException(&顺序表已满,无法添加&);
//是否需要?
测试代码:
public static void test() throws Exception
throw new Exception(&参数越界&);
System.out.println(&异常后&); //编译错误,「无法访问的语句」
throw new Exception(&参数越界&);
system.out.println(&继续执行后续代码&); //前面抛出异常,不能执行
}catch(Exception e) {
e.printStackTrace();
System.out.println(&异常后&);//可以执行
if(true) {
throw new Exception(&参数越界&);
System.out.println(&异常后&); //抛出异常,不会执行
若一段代码前有异常抛出,并且这个异常没有被捕获,这段代码将产生编译时错误「无法访问的语句」。如代码1 若一段代码前有异常抛出,并且这个异常被try&catch所捕获,如代码2,则有两种情况:
若该代码在try中抛出异常位置之后,则不执行; 若在整个try-catch之后,且catch语句中没有抛出新的异常,则这段代码能够被执行,否则,同第1条。 若在一个条件语句中抛出异常,则程序能被编译,但后面的语句不会被执行。如代码3
运行时异常与非运行时异常
运行时异常是RuntimeException类及其子类的异常,是非受检异常,如NullPointerException、IndexOutOfBoundsException等。由于这类异常要么是异常,无法处理,如网络问题;
要么是程序逻辑错误,如空指针异常;JVM必须停止运行以改正这种错误,所以运行时异常可以不进行处理(捕获或向上抛出,当然也可以处理),而由JVM自行处理。 Runtime会自动catch到程序throw的RuntimeException,然后停止线程,打印异常。 非运行时异常是RuntimeException以外的异常,类型上都属于Exception类及其子类,是受检异常。非运行时异常必须进行处理(捕获或向上抛出),如果不处理,程序将出现编译错误。一般情况下,API中写了throws的Exception都不是RuntimeException。
常见运行时异常
常见非运行时异常在 SegmentFault,解决技术问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
一线的工程师、著名开源项目的作者们,都在这里:
获取验证码
已有账号?
问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
Exception in thread "main" java.lang.NoClassDefFoundError: Product (wrong name: bluej/Product)
product.java
* Model some details of a product sold by a company.
* @author David J. Barnes and Michael Kolling
* @version
public class Product {
// An identifying number for this product.
// The name of this product.
// The quantity of this product in stock.
* Constructor for objects of class Product.
* The initial stock quantity is zero.
* @param id The product's identifying number.
* @param name The product's name.
public Product(int id, String name) {
this.name =
quantity = 0;
* @return The product's id.
public int getID() {
* @return The product's name.
public String getName() {
* @return The quantity in stock.
public int getQuantity() {
* @return The id, name and quantity in stock.
public String toString() {
return id + ": " +
" stock level: " +
* Restock with the given amount of this product.
* The current quantity is incremented by the given amount.
* @param amount The number of new items added to the stock.
This must be greater than zero.
public void increaseQuantity(int amount) {
if(amount & 0) {
quantity +=
System.out.println("Attempt to restock " +
" with a non-positive amount: " +
* Sell one of these products.
* An error is reported if there appears to be no stock.
public void sellOne() {
if(quantity & 0) {
quantity--;
System.out.println("Attempt to sell an out of stock item: " + name);
StockDemo.java
import bluej.StockM
import bluej.P
* Demonstrate the StockManager and Product classes.
* The demonstration becomes properly functional as
* the StockManager class is completed.
* @author David J. Barnes and Michael Kolling
* @version
public class StockDemo
// The stock manager.
private StockM
* Create a StockManager and populate it with a few
* sample products.
public StockDemo()
manager = new StockManager();
manager.addProduct(new Product(132, "Clock Radio"));
manager.addProduct(new Product(37,
"Mobile Phone"));
manager.addProduct(new Product(23,
"Microwave Oven"));
* Provide a very simple demonstration of how a StockManager
* might be used. Details of one product are shown, the
* product is restocked, and then the details are shown again.
public void demo()
// Show details of all of the products.
manager.printProductDetails();
// Take delivery of 5 items of one of the products.
manager.delivery(132, 5);
manager.printProductDetails();
* Show details of the given product. If found,
* its name and stock quantity will be shown.
* @param id The ID of the product to look for.
public void showDetails(int id)
Product product = getProduct(id);
if(product != null) {
System.out.println(product.toString());
* Sell one of the given item.
* Show the before and after status of the product.
* @param id The ID of the product being sold.
public void sellProduct(int id)
Product product = getProduct(id);
if(product != null) {
showDetails(id);
product.sellOne();
showDetails(id);
* Get the product with the given id from the manager.
* An error message is printed if there is no match.
* @param id The ID of the product.
* @return The Product, or null if no matching one is found.
public Product getProduct(int id)
Product product = manager.findProduct(id);
if(product == null) {
System.out.println("Product with ID: " + id +
" is not recognised.");
* @return The stock manager.
public StockManager getManager()
public static void main(String[] args) {
StockDemo w = new StockDemo();
w.showDetails(23);
w.sellProduct(132);
StockManage.java
import bluej.P
import java.util.ArrayL
* Manage the stock in a business.
* The stock is described by zero or more Products.
* @author (your name)
* @version (a version number or a date)
public class StockManager
// A list of the products.
private ArrayList&Product&
* Initialise the stock manager.
public StockManager()
stock = new ArrayList&Product&();
* Add a product to the list.
* @param item The item to be added.
public void addProduct(Product item)
for (int i = 0;i & stock.size();i++) {
if (item.getID() == stock.get(i).getID()) {
while (i == stock.size() - 1) {
stock.add(item);
* Receive a delivery of a particular product.
* Increase the quantity of the product by the given amount.
* @param id The ID of the product.
* @param amount The amount to increase the quantity by.
public void delivery(int id, int amount)
Product pro = findProduct(id);
pro.increaseQuantity(amount);
* Try to find a product in the stock with the given id.
* @return The identified product, or null if there is none
with a matching ID.
public Product findProduct(int id)
Product p =
for (int i = 0;i & stock.size();i++) {
if (stock.get(i).getID() == id) {
p = stock.get(i);
* Locate a product with the given ID, and return how
* many of this item are in stock. If the ID does not
* match any product, return zero.
* @param id The ID of the product.
* @return The quantity of the given product in stock.
public int numberInStock(int id)
int number = 0;
for (int i = 0;i & stock.size();i++) {
if (stock.get(i).getID() == id) {
if (number == 0) {
* Print details of all the products.
public void printProductDetails()
for (int i = 0;i & stock.size();i++) {
System.out.println("Product:" + (i + 1) + "Information:" +stock.get(i).toString());
* Find product by getting the name of product
public Product findProductByName(String name) {
Product n =
for (int i = 0;i & stock.size();i++) {
if (name == stock.get(i).getName()) {
n = stock.get(i);
public void printLowStockProducts(int lowsize)
for (int i = 0;i & stock.size();i++) {
if(stock.get(i).getQuantity() & lowsize){
System.out.println("Product:" + (i + 1) + "Information:" +stock.get(i).toString());
main函数在StockDemo.java中,但无法运行!!!
错误如下:
Exception in thread "main" java.lang.NoClassDefFoundError: Product (wrong name: bluej/Product)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2625)
at java.lang.Class.getMethod0(Class.java:2866)
at java.lang.Class.getMethod(Class.java:1676)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
我把你的代码copy了一份运行了一下,没有报找不到类的错,可能找不到类的问题多半确实如楼上所说,没有编译,但是我的代码编译后运行还是报错,报的空指针的
简单看了一下你报错的地方,是查询完product,再去增加库存的时候,prod为null,所以报错
为啥prod为null,是因为debug可以看到,你的manager类初始化后的prod集合为空,所以根据id找不到对应的prod
有待改进问题一:根据id去查询数据后,本身查询方法默认的初始值就是null了,所以在调用查询方法时,就本身应该考虑这个查询方法是可能返回null的,所以应该要再调用完查询方法后,首先检查一下是否为null,再做后续操作
那为啥这个manager类里的prod集合大小为0呢?你前面也有增加prod的操作的
其实问题就是出在这个manager增加prod的方法里,查看StockManager.addProduct
可以看到,你的逻辑估计是想做图上所说的两个事,但是这样做,有些问题有待改进问题二:最开始的时候集合stock就是空的,所以第一次addprodcut的时候,这个for循环就走不进去,所以后续也走不进去,因为你的stock.add方法写在循环里了,所以stock集合一直为空有待改进问题三:list集合本身add方法默认就是添加到集合最后的,所以没有必要去判断循环的位置,只要前面检验id不同了,就可以直接调用所以建议以下修改:
修改后,程序看起来是正常了,起码没有报错,至于业务上(比如库存)是否有问题,你自己再多多斟酌一下
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
请问你编译了吗
同步到新浪微博
分享到微博?
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:}

我要回帖

更多关于 java代码运行 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信