Finally block
package com.myjava.exceptions;
public class myfinallyblock
{
public static void
main(string[] a)
{
try
{
int
i = 10/0;
}
catch(exception ex)
{
system.out.println("Inside
1st catch Block");
}
finally
{
system.out.println("Inside
1st finally block");
}
try
{
int
i = 10/10;
}
catch(exception ex)
{
system.out.println("Inside
2nd catch Block");
}
finally
{
system.out.println("Inside
2nd finally block");
}
}
}
Without catch block
package com.myjava.exceptions;
public class myownexception
{
public static void
main(string[] a)
{
try
{
myownexception.mytest(null);
}
catch(myappexception
mae)
{
system.out.println("Inside
catch block: "+mae.getmessage());
}
}
static void mytest(string
str) throws myappexception
{
if(str
== null)
{
throw
new myappexception("string val is null");
}
}
}
class myappexception extends exception
{
private string message
= null;
public myappexception()
{
super();
}
public myappexception(string
message)
{
super(message);
this.message
= message;
}
public myappexception(throwable
cause)
{
super(cause);
}
public
string tostring()
{
return
message;
}
public string
getmessage()
{
return
message;
}
}
Custom Exception
import java.util.scanner;
class division
{
public static void main(string[]
args)
{
int a, b, result;
scanner input = new
scanner(system.in);
system.out.println("Input
two integers");
a =
input.nextInt();
b =
input.nextInt();
result
= a / b;
system.out.println("Result
= " + result);
}
}
Java Thread by Implementing Runnable Interface
package com.myjava.threads;
class myrunnablethread implements runnable
{
public static int mycount
= 0;
public
myrunnablethread()
{
}
public void run()
{
while(myrunnablethread.mycount
<= 10)
{
try
{
system.out.println("Expl
Thread: "+(++myrunnablethread.mycount));
thread.sleep(100);
}
catch (interruptedexception iex)
{
system.out.println("Exception
in thread: "+iex.getmessage());
}
}
}
}
public class runmythread
{
public static void
main(string a[])
{
system.out.println("Starting
Main Thread...");
myrunnablethread
mrt = new myrunnablethread();
thread
t = new thread(mrt);
t.start();
while(myrunnablethread.mycount
<= 10)
{
try
{
system.out.println("Main
Thread: "+(++myrunnablethread.mycount));
thread.sleep(100);
}
catch (interruptedexception iex)
{
system.out.println("Exception
in main thread: "+iex.getmessage());
}
}
system.out.println("End
of Main Thread...");
}
}
No comments:
Post a Comment