Sumber: Sedheng Pandhuan iki njlèntrèhaké keuntungan saka try-with-resource tinimbang try-catch-final. Sampeyan uga bakal sinau ing kahanan apa pengecualian sing ditindhes dibuwang lan cara nggunakake coba-kanggo-sumber daya kanthi macem-macem sumber daya.
Konstruksi try with resources , uga dikenal minangka try-with-resources , minangka mekanisme pangecualian ing Jawa sing bisa nutup sumber daya kanthi otomatis kayata Java InputStream utawa JDBC Connection yen wis rampung nggarap. Ing 2011, Oracle nambahake nyoba nganggo sumber daya menyang sintaks basa Jawa kanggo mesthekake yen obyek kayata soket jaringan, sambungan database, lan pranala file lan folder ditutup kanthi apik sawise digunakake. Gagal nutup sumber daya kasebut sawise pangembang mbukak gagang bisa nyebabake kebocoran memori, nyebabake rutinitas pengumpulan sampah sing bisa dicegah, lan overhead CPU ing server.
![Ngopi #203. Cara nangani pengecualian nggunakake statement try-with-resource - 1](https://cdn.javarush.com/images/article/2b752b4c-ec83-470e-a68f-44ddf61a7b7f/800.jpeg)
Sadurunge Jawa 7
Ing Jawa, yen sampeyan nggunakake sumber daya kayata input / output stream, sampeyan kudu tansah nutup sawise nggunakake. Wiwit padha uga bisa mbuwang pangecualian, padha kudu ana ing blok nyoba-nyekel . Panutup kudu kedadeyan ing blok pungkasan . Paling ora nganti Jawa 7. Nanging ana sawetara kekurangan:- Sampeyan kudu mriksa manawa sumber daya sampeyan null sadurunge nutup.
- Panutup dhewe bisa mbuwang pangecualian, dadi sampeyan kudu nyoba-nyekel liyane ing blok pungkasan sampeyan .
- Programer cenderung lali kanggo nutup sumber daya.
Kepiye cara nggunakake statement try-with-resource?
Operator iki wiwitane dikenalake ing Java 7 lan ide kasebut yaiku para pangembang ora perlu kuwatir babagan ngatur sumber daya sing digunakake ing blok nyoba-nyekel-akhire . Iki digayuh kanthi ngilangi kabutuhan pamblokiran pungkasan , sing ing praktik mung digunakake dening pangembang kanggo nutup sumber daya. Ing Jawa, statement try-with-resources minangka statement try sing nyatakake siji utawa luwih sumber daya. Sumber daya minangka obyek sing kudu ditutup sawise program rampung. Nalika eksekusi kode ninggalake blok try-with-resources , sumber apa wae sing dibukak ing blok try-with-resources bakal ditutup kanthi otomatis, ora preduli manawa ana pangecualian sing dibuwang ing blok try-with-resources utawa nalika nyoba nutup sumber daya. . Kanggo nggunakake fitur basa Java try-with-resources , aturan ing ngisor iki ditrapake:- Kabeh obyek sing dikontrol dening statement try-with-resources kudu ngetrapake antarmuka AutoCloseable .
- Multiple AutoCloseable objects bisa digawe ing blok try-with-resources .
- Obyek sing diumumake ing statement try-with-resources dieksekusi ing try block , nanging ora ing catch utawa pungkasane blok .
- Cara cedhak () obyek sing diumumake ing blok coba-karo-sumber daya diarani preduli saka apa pengecualian dibuwang nalika runtime.
- Yen pangecualian dibuwang ing cedhak () cara , bisa diklasifikasikaké minangka istiméwa ditindhes.
Sintaksis
try(declare resources here) {
// использовать ресурсы
}
catch(FileNotFoundException e) {
// обработка исключений
}
Panggunaan praktis saka try-with-resource
Kanggo nutup kanthi otomatis, sumber daya kudu diumumake lan diwiwiti ing coba :try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
writer.println("Hello World");
}
Ganti try-catch-finals karo try-with-resources
Cara sing gampang lan jelas kanggo nggunakake fungsi coba-kanggo-sumber daya yaiku ngganti blok tradisional lan verbose try-catch-finally . Ayo mbandhingake conto kode ing ngisor iki. Conto pisanan minangka blok try-catch-finally khas :Scanner scanner = null;
try {
scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
Lan iki solusi super ringkes anyar nggunakake try-with-resources :
try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
Bedane antarane nyoba lan nyoba-karo-sumber
Nalika nerangake pangecualian, ana bedane antarane blok nyoba-nyekel-pamungkas lan blok nyoba-karo-sumber . Pangecualian dibuwang ing nyoba lan pungkasane mblokir , nanging cara kasebut ngasilake pangecualian sing dibuwang mung ing blok pungkasan . Kanggo try-with-resources , yen ana pangecualian ing blok try lan ing statement try-with-resources , cara kasebut ngasilake pangecualian sing dibuwang ing blok try . Pengecualian sing dibuwang dening blok try-with-resources ditindhes, yaiku, kita bisa ngomong yen blok try-with-resources mbuwang pengecualian sing ditindhes.Napa aku kudu nggunakake statement try-with-resource?
Pernyataan try-with-resources njamin yen saben sumber ditutup ing pungkasan statement. Yen kita ora nutup sumber daya, iki bisa nyebabake kebocoran sumber daya lan program bisa kesel sumber daya sing kasedhiya. Iki kedadeyan nalika sampeyan nggunakake blok try-catch-finally . Sadurunge Java SE 7, sampeyan bisa nggunakake pamblokiran pungkasan kanggo mesthekake yen sumber daya bakal ditutup preduli saka statement nyoba metu biasane utawa dumadakan. Conto ing ngisor iki nggunakake blok pungkasan tinimbang pernyataan coba-kanggo-sumber :static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
try {
return br.readLine();
} finally {
br.close();
fr.close();
}
}
Bisa uga ana bocor sumber daya ing conto iki. Program kasebut kudu nindakake luwih saka mung gumantung ing tukang sampah kanggo mbebasake memori sumber daya sawise rampung nggunakake. Program kasebut uga kudu ngasilake sumber daya menyang sistem operasi, biasane kanthi nelpon metode cedhak sumber kasebut. Nanging, yen program ora nindakake iki sadurunge kolektor sampah ngasilake sumber daya, informasi sing dibutuhake kanggo mbebasake sumber daya bakal ilang. Sumber daya bocor sing isih dianggep sistem operasi digunakake. Ing conto ditampilake ing ndhuwur, yen cara readLine mbalang pangecualian lan br.close () statement ing pungkasan pemblokiran mbalang pangecualian, banjur FileReader wis bocor . Mulane sampeyan luwih apik nggunakake statement nyoba-karo-sumber tinimbang blok pungkasan kanggo nutup sumber daya program sampeyan.
Conto liyane
Conto ing ngisor iki maca baris pisanan saka file. Instance FileReader lan BufferedReader digunakake kanggo maca data . Iki minangka sumber daya sing kudu ditutup sawise program metu.import java.io.*;
class Main {
public static void main(String[] args) {
String line;
try(BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
while ((line = br.readLine()) != null) {
System.out.println("Line =>"+line);
}
} catch (IOException e) {
System.out.println("IOException in try block =>" + e.getMessage());
}
}
}
Kaya sing sampeyan ngerteni, sumber daya sing diumumake ing statement try-with-resources yaiku BufferedReader . Pranyatan pranyatan kanggo sumber iki katon ing kurung sanalika sawise tembung kunci nyoba . Kelas BufferedReader ing Java SE 7 lan mengko ngleksanakake antarmuka java.lang.AutoCloseable . Amarga kedadean BufferedReader diumumake ing statement nyoba-karo-sumber daya , padha bakal ditutup preduli saka statement nyoba metu biasane utawa dumadakan (yen BufferedReader.readLine () cara mbalang IOException ).
Pangecualian sing ditindhes
Yen blok coba mbuwang pangecualian, lan siji utawa luwih pangecualian katon ing blok coba-kanggo-sumber daya , banjur pangecualian sing dibuwang dening blok coba-kanggo-sumber daya bakal ditindhes. Ing tembung liyane, kita bisa ngomong yen pangecualian sing dibuwang dening try-with-resources minangka pangecualian sing ditindhes. Sampeyan bisa nyekel pangecualian iki nggunakake metode getSuppress () saka kelas Throwable . Ing conto sing dituduhake sadurunge, pangecualian dibuwang dening statement try-with-resources , ing kahanan ing ngisor iki:- File test.txt ora ditemokake.
- Nutup obyek BufferedReader .
Njupuk pengecualian sing ditindhes
Ing Jawa 7 lan mengko, istiméwa ditindhes bisa dipikolehi kanthi nelpon Throwable.getSuppressed () cara saka pangecualian di buwang dening pemblokiran nyoba . getSuppress() ngasilake array sing ngemot kabeh pangecualian sing ditindhes dening statement try-with-resources . Yen ora ana pangecualian sing ditindhes utawa dipateni, array kosong bakal bali. Iki minangka conto nampa pangecualian sing ditindhes ing blok tangkapan :catch(IOException e) {
System.out.println("Thrown exception=>" + e.getMessage());
Throwable[] suppressedExceptions = e.getSuppressed();
for (int i=0; i" + suppressedExceptions[i]);
}
}
Keuntungan nggunakake sumber daya nyoba
- Kode sing bisa diwaca lan gampang ditulis. Manajemen sumber daya otomatis.
- Jumlah baris kode wis suda.
- Nalika macem-macem sumber dibukak ing try-with-resources , padha ditutup ing urutan mbalikke kanggo ngindhari masalah ketergantungan.
import java.io.*;
class Main {
public static void main(String[] args) {
BufferedReader br = null;
String line;
try {
System.out.println("Entering try block");
br = new BufferedReader(new FileReader("test.txt"));
while ((line = br.readLine()) != null) {
System.out.println("Line =>"+line);
}
} catch (IOException e) {
System.out.println("IOException in try block =>" + e.getMessage());
} finally {
System.out.println("Entering finally block");
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
System.out.println("IOException in finally block =>"+e.getMessage());
}
}
}
}
Kesimpulan:
Ngetik try block Line =>line from test.txt file Entering finally block
Kaya sing sampeyan ngerteni saka conto ing ndhuwur, nggunakake blok pungkasan kanggo ngresiki sumber daya nambah kerumitan kode kasebut. Wigati nyoba ... nyekel blok ing pungkasan blok ? Iki amarga IOException uga bisa kedadeyan nalika nutup conto BufferedReader ing pamblokiran pungkasan , mula uga kejiret lan ditangani. Pernyataan try-with-resources nindakake manajemen sumber daya otomatis. Kita ora perlu nutup sumber daya kanthi jelas amarga JVM nutup kanthi otomatis. Iki nggawe kode luwih gampang diwaca lan luwih gampang ditulis.
Coba-karo-sumber daya kanthi macem-macem sumber daya
Kita bisa ngumumake macem-macem sumber daya ing blok try-with-resources kanthi misahake kanthi titik koma:try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}
Jawa 9 - Variabel pungkasan kanthi efektif
Sadurunge Java 9, kita mung bisa nggunakake variabel seger ing blok try-with-resources :try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
// omitted
}
Elinga yen iki cukup verbose nalika ngumumake macem-macem sumber daya. Wiwit Java 9 (update JEP 213), kita bisa nggunakake variabel final utawa malah kanthi efektif ing blok try-with-resources :
final Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))
try (scanner;writer) {
// omitted
}
Cukup, variabel efektif final yen ora diowahi sawise tugas pisanan, sanajan ora kanthi tegas ditandhani final . Kaya sing dituduhake ing ndhuwur, variabel pemindai diumumake kanthi jelas dadi final supaya bisa digunakake kanthi blok coba-kanggo-sumber . Senajan variabel writer ora eksplisit final , iku ora ngganti sawise assignment pisanan. Dadi kita uga bisa nggunakake variabel panulis . Muga-muga dina iki sampeyan entuk pangerten sing luwih apik babagan cara nangani pangecualian nggunakake statement try-with-resource . Sugeng sinau!
GO TO FULL VERSION