"Aku arep nyritakake babagan cara pangecualian . Conto ing ngisor iki kudu menehi gambaran kasar babagan apa sing kedadeyan: "
class ExceptionExampleOriginal
{
public static void main(String[] args)
{
System.out.println("main begin");
try
{
System.out.println("main before call");
method1();
System.out.println("main after call");
}
catch (RuntimeException e)
{
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main end");
}
public static void method1()
{
System.out.println("method1 begin");
method2();
System.out.println("method1 end");
}
public static void method2()
{
System.out.println("method2");
String s = "Message: Unknown Exception";
throw new RuntimeException(s);
}
}
public class ExceptionExample
{
private static Exception exception = null;
public static void main(String[] args)
{
System.out.println("main begin");
System.out.println("main before call");
method1();
if (exception == null)
{
System.out.println("main after call");
}
else if (exception instanceof RuntimeException)
{
RuntimeException e = (RuntimeException) exception;
exception = null;
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main end");
}
public static void method1()
{
System.out.println("method1 begin");
method2();
if (exception != null) return;
System.out.println("method1 end");
}
public static void method2()
{
System.out.println("method2");
String s = "Message: Unknown Exception";
exception = new RuntimeException(s);
return;
}
}
"Aku pancen ilang."
"Inggih. Ayo kula nerangake apa sing kedadeyan."
"Ing conto ing sisih kiwa, kita nelpon sawetara cara ing kasuksesan. Ing method2
, kita sengaja nggawe lan uncalan pangecualian (kita nggawe kesalahan)."
"Conto ing sisih tengen nuduhake apa sing kedadeyan."
"Deleng ing method2
. Tinimbang nggawe pangecualian, kita nggawe RuntimeException
obyek, simpen menyang variabel statis exception
, banjur langsung metu saka metode nggunakake return
statement."
"Ing method1
, sawise nelpon method2
, kita mriksa apa ana pangecualian. Yen ana pangecualian, banjur method1
ends bebarengan. A mriksa kaya iki dileksanakake ora langsung sawise saben (!) panggilan metode ing Jawa."
"Wah!"
"Wah bener."
"Ing kolom sisih tengen, aku wis nggunakake cara utama kanggo nuduhake kira-kira apa sing kedadeyan nalika pangecualian kejiret nggunakake konstruksi nyoba-nyekel. Yen ora ana pangecualian, kabeh bakal terus mlaku kaya sing dikarepake. Yen ana pangecualian lan yaiku jinis sing padha sing ditemtokake ing statement catch, banjur kita nangani.
"Apa tegese throw
lan apa instanceof
? "
"Deleng baris pungkasan: throw new RuntimeException(s);
. Iki carane nggawe lan uncalan pangecualian. Kita ora bakal bisa ing. Iku mung conto."
"We digunakake a instanceof B
kanggo mriksa apa obyek a
saka jinis B
, IE apa obyek referensi dening istiméwa variabel punika RuntimeException. Iki ekspresi boolean."
"Aku rumangsa entuk. Meh."
GO TO FULL VERSION