Ukhetho lweJava kunye nendlela yokujongana nayo

Njengomphuhlisi weJava, kuya kufuneka ube unolwazi olufanelekileyo lokhetho lweJava kunye nokuphathwa ngaphandle.

Olu qeqesho lubonelela ngolwazi olusisiseko ekufuneka wonke umdwelisi wenkqubo xa enenkqubo zeJava. Ukuqala, masiqale ngokuqonda ukuba zeziphi kanye kanye izinto ezikhethiweyo zeJava.



Zithini iiJava ngaphandle

Inkqubo yeJava inokuba neengxaki ezibangela ukuba inkqubo ipheliswe ngesiquphe ngexesha lokuqhutywa kwayo. Ezi ngxaki zibizwa ngokuba zezangaphandle.


Umdwelisi nkqubo olungileyo kufuneka abenakho ukubona iimpazamo ezinokuthi zenzeke ngexesha lokuphunyezwa kunye nokubonelela ngeendlela ezizezinye zenkqubo eziza kuthatha kwimeko yolo khetho. Lo mkhuba ubizwa ngokuba kukuphatha ngokungafaniyo.

Ngoku unokuzibuza ukuba kutheni le nto sifuna ukusingathwa ngaphandle kokukhetha. Kutheni ungabhali iinkqubo ezingayi kulahla ngaphandle?




Kutheni le nto sifuna ukuPhathwa ngaphandle

Njengoko kuvela, ukubhala iinkqubo ezingayi kulahla ngaphandle akukho lula njengoko kuvakala. Uninzi lwexesha, ezi mpazamo zingenakuphepheka zingaphandle kolawulo lwenkqubo.



Iinkqubo ezamkela igalelo lomsebenzisi zithambekele ekusebenzeni ngaphandle ngenxa yegalelo elingavumelekanga elinikezelwa ngumsebenzisi. Kunjalo ngokufunda iifayile zangaphandle kuthathelwa ingqalelo ithuba lokuba zihanjisiwe, zinikwe elinye igama, okanye zisuswe ngumthombo wangaphandle ngaphandle kolwazi lwenkqubo.

Kwiimeko ezinjalo, inkqubo kufuneka ikwazi ukusingatha ngaphandle kokuyekisa ukwenziwa.



Uluhlu lwabaphathi beJava ngaphandle

Konke okwahlukileyo kwiJava kufanele ukuba kube ngumntwana Exception iklasi, ekwangumntwana wayo Throwable iklasi.


Iziqendu ezibini eziphambili ze Exception iklasi RuntimeException kunye IOException.



Ngaphandle kwempazamo

Olunye udidi lwabantwana lwe Throwable iklasi yilo Error iklasi. Nangona kunjalo, iimpazamo zahlukile ngaphandle.

Iimpazamo zibonisa iingxaki ezinokuthi zingene kwi-JVM ngexesha lokuqhutywa. Ezi ngxaki zihlala zibalulekile kwaye azinakufunyanwa. Ukuvuza kwenkumbulo kunye nemiba yokungahambelani kwethala leencwadi zizizathu eziqhelekileyo zeempazamo kwiinkqubo.

StackOverflowError kunye OutOfMemoryError yimizekelo emibini yeempazamo zeJava.




Kuqwalaselwe kwaye kungakhange kujongwe

Singahlulahlula i-Java Exceptions ibe ziindidi ezimbini eziphambili: itshekishiwe kwaye ayiqwalaselwanga ngaphandle.

Ukungqinisiswa kokutshekishwa ngaphandle ngaphandle kokufuna ukuphathwa kwinkqubo ngaphambi kokudityaniswa. Ukuba oku kungasetyenziswanga akuphathwanga, inkqubo ayizukuqulunqwa ngumhlanganisi weJava. Ke ngoko, zikwabizwa ngokuba kukudityaniswa kwexesha lokudityaniswa. IOExceptions yimizekelo elungileyo yokutshekishwa ngaphandle.

Ukhetho olungakhange luqwalaselwe zezona zingenziwa ngumqokeleli xa engayidibanisi nenkqubo. Nokuba sikwenzile oku ngaphandle kule nkqubo okanye akunjalo akunamsebenzi xa inkqubo idityaniswa. Kuba ukusingathwa ngokungafaniyo kunganyanzelwanga koku kungafaniyo, inkqubo yethu inokubaleka | | + _ | | ezikhokelela ekuphelisweni kwenkqubo.

Zonke iiklasi ezandisa RuntimeExceptions iklasi azikhathalelwanga. Imizekelo emibini yeeklasi ezinjalo zi _ _ + _ | kunye RuntimeException.




Iindlela eziqhelekileyo ezisetyenziswa kwiKlasi yokuKhuphela

Siza kuhamba ngeendlela ezimbalwa ezisetyenziswa ngokuxhaphakileyo kwiJava NullPointerException iklasi:

  1. ArrayIndexOutOfBoundsException: ubuyisela umyalezo oqulathe iinkcukacha malunga nokuchasene okwenzekileyo.
  2. Exception: ibuyisa umkhondo wesitaki ngaphandle kokuba yenzekile.
  3. getMessage: ubuyisela igama leklasi kunye nomyalezo obuyiswayo nge printStackTrace indlela.


Ukujongana njani nokuNgaphandle

Makhe sibone ukuba singazisingatha njani izinto ezikhethiweyo kwiJava:

zama ukubamba

Sinokubamba okwahlukileyo kwaye sikuphathe ngokufanelekileyo sisebenzisa i- zama ukubamba block kwiJava.

Kule syntax, icandelo lekhowudi elithanda ukuphosa ngaphandle libekwe ngaphakathi kwibloko yokuzama kwaye iibhloko zokubamba / iibhloksi zibambe okwahlukileyo okukhutshiweyo / ngaphandle kwaye baziphathe ngokomgaqo esiwunika wona.


Is syntax esisiseko sebhlokhi yokubamba ngolu hlobo lulandelayo:

toString

Ngale ndlela, le nkqubo ayimisi ukwenziwa xa imeko iphoswa yinkqubo, endaweni yoko iphathwa kakuhle.

Siza kubona indlela yokuphatha getMessage iphoswe | | + _ | iklasi kwinkqubo yeJava.

Umzekelo:

try {
//exception-prone code } catch(Exception e) {
//error handling logic }

Apha, sisebenzise ibhloko enye yokubamba ukuphatha IOExceptions iphoswe xa iqinisekisa FileReader iklasi kunye import java.io.FileReader; public class TryCatchBlockExample {
public static void main(String[] args) {

try {

FileReader file = new FileReader('source.txt');

file.read();
}
catch(Exception e) {

e.printStackTrace();
}
} }
iphoswe | | + _ | indlela ye FileNotFoundException iklasi.

Zombini ezi zinto zikhethiweyo ngabantwana be FileReader iklasi.

Sinokusebenzisa iingxelo ezininzi zokubamba ukubamba iintlobo ezahlukeneyo zeempazamo eziphoswe yikhowudi ngaphakathi kwisitatimende esinye sokuzama. Kumzekelo wangaphambili, singasebenzisa ibhloko enye yokubamba ukubamba IOException kunye nenye ibhlokhi yokubambisa read() njengoko le khowudi ilandelayo ibonisa:

FileReader

Ukuba okhutshiweyo kungqinelana nokungaphathwa kwesitetimenti sokuqala sokubamba, emva koko siphathwa ngengqondo ngaphakathi kwengxelo yokuqala yokubamba.

Ukuba okwahlukileyo akuhambelani, kugqithiselwa kwingxelo yesibini yokubamba. Ukuba kukho iingxelo ezingaphezulu kwesibini zokubamba, le nkqubo iyaqhubeka kude kube ngaphandle kokufikelela kwisiteyitimenti sokubamba esabamba uhlobo lwaso.

Ukusukela Exception ludidi olungezantsi lwe FileNotFoundException, usebenzisa ingxelo yesi-2 yokubamba ukubamba IOException ayizukusebenza. Iya kuphathwa ngengxelo yokuqala yokubamba kwaye ungaze ufike kwingxelo yesi-2.

Phawula:Kuyanyanzeleka ukuba usebenzise ubuncinci isitatimenti sokubamba kunye nengxelo yokuzama.

ekugqibeleni

Xa sisebenzisa i zama ukubamba block ukubamba ngaphandle kwenkqubo yethu, kukho iimeko apho sifuna ukumilisela ingcinga ethile nangona inyani ibanjiwe okanye hayi. Kwiimeko ezinjalo, sinokusebenzisa ifayile ye- zama ukubamba-ekugqibeleni block endaweni yokuba nje zama ukubamba ibhloko.

Ke ikhowudi ngaphakathi import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class TryCatchBlockExample {
public static void main(String[] args) {

try {

FileReader file = new FileReader('source.txt');

file.read();

file.close();
}
catch(FileNotFoundException e) {

e.printStackTrace();
}
catch(IOException e) {

e.printStackTrace();
}
} }
Isiteyitimenti siyaphunyezwa nokuba kwenzeka ngaphandle okanye hayi. I FileNotFoundException Isiteyitimenti kufuneka sihlale siza esiphelweni sebloko lokuzama ukubamba.

Umzekelo, xa sisebenzisa IOException iklasi yokufunda ifayile, kubalulekile ukuvala ifayile evuliweyo ekugqibeleni kokuqhubekeka nokuba kwenzeka okwahlukileyo okanye hayi. Ukuqinisekisa oku, singabeka ikhowudi ukuvala ifayile ngaphakathi | FileNotFoundException ingxelo.

finally

Nangona kunjalo, ukuba uzama ukuqokelela le khowudi ingentla, ikhowudi ayinakuqulunqwa ngenxa yokungaphathwanga finally. Kungenxa yokuba FileReader indlela ye finally iklasi nayo inokuphosa import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class TryCatchFinallyBlockExample {
public static void main(String[] args) {
FileReader file = null;
try {

file = new FileReader('source.txt');

file.read();
}
catch(FileNotFoundException e) {

e.printStackTrace();
}
catch(IOException e) {

e.printStackTrace();
}
finally {

file.close();
}
} }
. Ke, kufuneka sibeke eli candelo ngaphakathi kwelinye ibhloko lokuzama ngolu hlobo:

IOException

ukuphosa

Ukusingatha iimpazamo usebenzisa close() igama eliphambili kwiJava lilula. Ngapha koko, kule ndlela, awuphathi ngokungafaniyo kwindawo eyenzeka kuyo. Endaweni yoko, siphosa ngaphandle kwendlela yangoku kwindlela ebizwa ngokuba yindlela yangoku. Emva koko, ukuhambisa impazamo iba luxanduva lwangaphandle.

Ukuphosa ngaphandle kwendlela, kuya kufuneka ubhengeze ukuba le ndlela inokuphosa okwahlukileyo. Makhe sibone ukuba singayiphatha njani FileReader iphoswe | | + _ | iklasi isebenzisa le ndlela.

Umzekelo:

IOExceptions

jula

Ngokungafaniyo nezinye iindlela ezikolu luhlu, import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class TryCatchFinallyBlockExample {
public static void main(String[] args) {
FileReader file = null;

try {

file = new FileReader('source.txt');

file.read();
}
catch(FileNotFoundException e) {

e.printStackTrace();
}
catch(IOException e) {

e.printStackTrace();
}
finally {

try {


file.close();

}

catch(IOException e) {


e.printStackTrace();

}
}
} }
igama eliphambili alisetyenziswanga ukuphatha iimpazamo. Kodwa kuba uninzi lwabantu luphazamisa throws igama eliphambili nge IOExceptions igama eliphambili, sicinge ukuba kuya kuba ngcono ukuxoxa ngalo apha.

I FileReader igama eliphambili lisetyenziselwa ukubiza ngokucacileyo okwahlukileyo. Sinokuphosa ngaphandle okuqinisekisiweyo okanye okwahlukileyo okubanjiweyo ngaphakathi kwendlela.

import java.io.FileReader; import java.io.IOException; public class ThrowsExample {
public void readFile throws IOException {
FileReader file = new FileReader('source.txt');
file.read();
file.close();
} }


Imeko ezichaziweyo zomsebenzisi

Ukongeza ekusebenziseni izinto ezakhelweyo ngaphakathi kwiJava, unokuchaza okwahlukileyo. Ungabachaza njengokukhangela okanye okungakhange kuhlolwe. Ukwenza into entsha ekhangelwe ngaphandle, okwahlukileyo kukhetho lwakho kufuneka kwandise throw iklasi.

Ukwenza ifayile ye- engaqwalaselwanga ngaphandle, yandisa throw iklasi.

Kulo mzekelo wekhowudi ulandelayo, senze into echaziweyo yomsebenzisi echongiweyo:

throws

Ngoku singasebenzisa oku kungasentla ngentla ngaphakathi kwenkqubo yethu enje:

throw

Ukuba sijonga ubude bomtya usebenzisa public class ThrowExample {
public void invalidate(int amount) throws Exception {
if (amount < 500) {

throw new Exception('Amount not sufficient');
}
} }
iklasi, iya kuphosa Exception ukuba ubude bomtya bungaphantsi kobude obuncinci okanye ngaphezulu kobude obuphezulu.

RuntimeException

Xa sisebenzisa le khowudi ikhowudi ingasentla, iya kuphosa public class InvalidLengthException extends Exception {
private int length;
private String message;
public InvalidLengthException(int length, String message) {
this.length=length;
this.message=message;
}
public int getAmount() {
return this.length;
}
public String getMessage() {
return this.message;
} }
kwaye siya kufumana iziphumo ezilandelayo:

public class InputChecker {
private int minLength;
private int maxLength;
public InputChecker(int minLength, int maxLength) {
this.minLength=minLength;
this.maxLength=maxLength;
}
public void checkStringLength(String strInput) throws InvalidLengthException {
int strLength = strInput.length();
if (strLength maxLength){

throw new InvalidLengthException(strLength, 'Input should have maximum '+maxLength+' character');
}
} }


Isiphelo

Kwesi sifundo, sikunike intshayelelo ekhawulezayo kunye nemfutshane kwizinto ezikhethiweyo zeJava. Siyathemba ukuba ngoku unokuqonda okuhle kokungafaniyo kunye nendlela yokuphatha kwinkqubo yakho yeJava.