有没有办法简化另一个try-catch-finally块中的try-catch块?

时间:2016-02-25 03:51:06

标签: java exception exception-handling try-catch

我是Java的新手,正在尝试学习捕获异常的概念。我在网上看到了这个代码,它在另一个try-catch-finally块的体内有一个try-catch块。我只是想知道是否有任何方法可以简化代码,以便能够以更清晰的方式编写代码?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize

class CustomNorm(Normalize):
    def __init__(self, levels, func, clip=None):
        # input levels
        self._levels = np.linspace(min(levels), max(levels), 10)
        # corresponding normalized values between 0 and 1
        self._normed = func(self._levels)
        Normalize.__init__(self, None, None, clip)

    def __call__(self, value, clip=None):
        # linearly interpolate to get the normalized value
        return np.ma.masked_array(np.interp(value, self._levels, self._normed))

    def inverse(self, value):
        return 1.0 - self.__call__(value)

def func(x):
    # whatever function, just normalise x into a sub-field of [0,1], 
    # it can be even [0,0.5]
    return x/50.0/2.0

y, x = np.mgrid[0.0:3.0:100j, 0.0:5.0:100j]
H = 50.0 * np.exp( -(x**2 + y**2) / 4.0 )
levels = [0, 1, 2, 3, 6, 9, 20, 50]
# levels = [0, 50]

# H1 = -50.0 * np.exp( -(x**2 + y**2) / 4.0 )
# levels1 = [-50, -20, -9, -6, -3, -2, -1, 0]
# levels1 = [-50, 0]

fig, ax = plt.subplots(2, 2, gridspec_kw={'width_ratios':(20, 1), 'wspace':0.05})

im0 = ax[0, 0].contourf(x, y, H, cmap='jet', norm=CustomNorm(levels, func))
cb0 = fig.colorbar(im0, cax=ax[0, 1])
# im1 = ax[1, 0].contourf(x, y, H1, levels1, cmap='jet', norm=CustomNorm(levels1, func))
# cb1 = fig.colorbar(im1, cax=ax[1, 1])

plt.show()

2 个答案:

答案 0 :(得分:2)

这确实是一种非常常见的模式,因此最近在Java中添加了一种特殊的语法:try-with-resources

你可以做到

try(OutputStream os1 = new FileOutputStream("xanadu123.properties")){
}
catch (WhatYouHadBefore e){}
// no more finally, unless you want it for something else

这将finally自动关闭(即使没有finally阻止),关闭期间的任何错误都将被取消。

答案 1 :(得分:1)

根据javadocs的说法,在Java SE 7及更高版本中,您可以使用try-with-resources,它将在资源完成时自动关闭资源。

public static void main(String[] args) {
    Properties p1 = new Properties();
    OutputStream os1 = null;
    try(os1 = new FileOutputStream("xanadu123.properties")){ //set the properties value
        p1.setProperty("database", "localhost");
        p1.setProperty("1", "one");
        p1.setProperty("2", "two");
        p1.store(os1, "this is the comment");
    } catch (IOException e) {
        e.printStackTrace();
    }
}