Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
View the Exhibit to examine the PL/SQL code.
SET serveroutput ON
DECLARE
past_due EXCEPTION;
acct_num NUMBER;
BEGIN
DECLARE
past_due EXCEPTION;
acct_num NUMBER;
due_date DATE := sysdate -1;
todays_date DATE := sysdate;
BEGIN
IF due_date < todays_date THEN
raise past_due;
END IF;
END;
EXCEPTION
WHEN past_due THEN
dbms_output.put_line('handling past_due exeption.');
WHEN OTHERS THEN
dbms_output.put_line('could not recognize rxception.');
END;
Which statement is true about the execution of the code?
A. The exception raised in the code is handled by the exception handler for the PAST_DUE
exception.
B. It does not execute because you cannot declare an exception with a similar name in the
subblock.
C. The PAST_DUE exception raised in the subblock causes the program to terminate abruptly
because there is no exception handler in the subblock.
D. The PAST_DUE exception raised by the enclosing block is not propagated to the outer block and it is handled by the WHEN OTHERS exception handler.
in the dumps the answer was C but i think its D
(D) is the closest to being correct, but even it's not really right. The past_due exception which is raised in the inner block is NOT the same past_due exception as is caught in the outer block. Thus, the inner block's past_due exception is caught by the outer block's OTHER handler. Try running the code and you'll see it prints "could not recognize rxception.". What's incorrect about answer (D) is that it says that "...the PAST_DUE exception...is not propagated to the outer block...". This is wrong - the exception is propagated to the outer block but as there's no specific handler for it (nor can there be as the context in which the exception was declared is not available) it's handled by the WHEN OTHERS... handler. Thus, in my opinion NONE of the answers is correct.
Share and enjoy.
As per me the answer is C because the Exception you are calling is not present in the block so will not be able to search for it and wont be able to raise it and will give some error.
Related
I'm making a custom plugin to query a database for user info to aide customer support. My backend is slack.
Everytime I start the bot command I'm greeted with:
Computer says nooo. See logs for details:
catching classes that do not inherit from BaseException is not allowed
I'm not sure if this is warning me that I'm attempting to catch an exception that isn't a BaseClass in my code or if an unknown exception was raised and caught elsewhere outside of my plugin.
To debug I tried:
try:
do_the_thing()
except (TypeError, ValueError) as e:
return('Something went wrong.')
I also tried:
try:
do_the_thing()
except Exception as e:
return('Something went wrong.')
And I still get the errbot admonition. Note that the command still runs and does the right thing where there is no exception raised by do_the_thing().
It means that:
Somewhere in your code you have an except ... statement where the exception ... (or one of the exceptions in the sequence ...) is not a subclass of BaseException, and
An exception is being thrown that is caught by that except ... statement.
The TypeError can be raised only when an exception is actually thrown because the names you give to except ... must be evaluated for their current values at that time; just because TypeError referenced a particular class at one point in the program's execution doesn't mean it won't be changed later to reference another object (though that would be admittedly perverse).
The Python interpreter should be giving you a full traceback of the exception; the first thing you need to do is find this. It could be occurring in one of two situations. (This is for single-threaded programs; I'm assuming your program is not multithreaded.)
During the execution of your program, in which case the program will be terminated by the exception, or
During finalization of objects (in their __del__(self) functions) in which case the error will be printed to stderr.
In both cases there should be a stack trace, not just the error message; I've confirmed that at least on Python ≥3.4 a stack trace is printed out for case 2.
You then need to follow this stack trace to see where the problem lies. Remember that the names you give to except ... are variables (even things like TypeError) that can be reassigned, so that you could conceivably be dealing with a (perverse) situation like:
TypeError = False
try:
...
except TypeError:
...
But more likely it will be something obvious such as:
class MyException: # Doesn't inherit from Exception
...
try:
...
except MyException:
...
There is one special case you need to be aware of: if you are seeing messages to stderr (case "2. During finalization," above) printed out as your program exits that means that the exception was thrown during cleanup as the interpreter shuts down, where random variables throughout the program may have already been set to None as part of the cleanup process. But in this case your program should still exit successfully.
I want to know why my program is behaving this way.
I have a method that throws an ArithmeticException when trying to divide by zero. I put this method in a try block. When it throws an exception, if at all, the proceeding catch block will catch this ArithmeticException.
I understand this part 100%.
But I did a bit of experimenting. In my method body:
public static int quotient(int number1, int number2) {
if (number2 == 0)
throw new ArithmeticException("Divisor cannot be zero!");
return number1 / number2;
}
I removed the third line. When I removed the third line, the program still ran fine and performed exactly as it did before. It still caught the ArithmeticException error when it occurred.
Is it because ArithmeticException is an unchecked exception and this error is caught only during runtime, thus negating the need for me to specifically declare that this program will cause an unchecked exception? If it was a checked exception, would I specifically need to declare that this method will throw an unchecked exception?
As you stated Arithmetic exception is a runtime exception, you do not need to specify that it throws an exception.
Although you do need to specify if your program throws a compile time exception using a throws statement. One example where you need to check the exception would be an IOException.
Exception is not being caught with its name but it is caught when others keyword is used? Below is my code
p.ads
package p is
procedure proc ;
end p;
p.adb
package body p is
my_exp:exception; -- user define exception
procedure proc is
begin
raise my_exp; -- spreading exception
end proc;
end p;
p_main.adb
with p;
with ada.text_io;
use ada.text_io;
use p;
procedure p_main is
begin
proc;
exception
when my_exp=>put(" my_exp");-- error but when others is used then.its good why?
end p_main;
A/c to adacore site my_exp is not visible here then how it is visible when others keyword is used?
Your code has numerous syntax errors. It's always better to copy-and-paste your exact code into the question; you appear to have re-typed it, which makes it difficult to distinguish between typos and actual errors in your original code.
Ignoring the syntax errors, this:
exception
when my_exp => put(" my_exp");
fails to compile because the name my_exp is not visible. (If you want it to be visible it should be in the package specification, but that's not what you asked.)
If you replace when my_exp by when others, it works; the exception is handled. This is because a when others clause handles any exception that's been raised, whether its name is visible or not.
An exception is a condition that exists when a program is running. The exception handler detects and handles that run-time entity. It doesn't need to refer to it by whatever identifier you used to define it.
If the name my_exp had been visible, the handler still (almost certainly) wouldn't use the name to identify the exception. Instead, the compiler creates some run-time data structure that allows exceptions to be identified, perhaps by a reference to a specific memory address. The exact mechanism depends on the compiler, and understanding the details is not terribly important unless you're writing a compiler.
The run-time detection that an exception has been raised, and which exception it is, does not depend on the name you've assigned to the exception in your source code.
The reference to the name my_exp is rejected at compile time because that name is not visible at compile time.
The first thing to understand is that if your package can raise a custom exception which isn't advertised by the package specification, that is bad design because it leads to unpleasant surprises for the package users.
So the right thing to do is to declare my_exp in the package instead of hiding it in the body.
package p is
my_exp:exception; -- user define exception
procedure proc ;
end p;
And then fix all the other trivial syntax errors, and your program works as advertised.
But even if you don't, and "my_exp" is not visible in the main program, its exception handler can identify it correctly.
procedure p_main is
begin
proc;
end p_main;
./p_main
raised P.MY_EXP : p.adb:7
Or you can manipulate that information yourself, for better diagnostics or error recovery
with Ada.Exceptions; -- we need to process exception data
procedure p_main is
begin
proc;
exception
when E : others =>
put("something bad happened : " & Ada.Exceptions.Exception_Name(E));
end p_main;
./p_main
something bad happened : P.MY_EXP
A comment by a high rep user on another question I asked earlier today suggested it would be better to swap the order of try/finally and try/except.
So, instead of this:
try
try
//some code
//something that throws an exception, eg: EIndexOutOfRangeException
//more code
except on E : EIndexOutOfRangeException do begin .... end;
finally
// some cleanup code
end;
it would have the try/finally nested inside and the try/except on the outside:
try
try
//some code
//something that throws an exception, eg: EIndexOutOfRangeException
//more code
finally
// some cleanup code
end;
except on E : EIndexOutOfRangeException do begin .... end;
end;
I would like to know when is it appropriate and a good idea to use this idiom, and are there exceptional cases where you shouldn't? Why prefer one over the other? I suppose exceptions being thrown in the cleanup code would be the main consideration, since I imagine it could suppress one of the exceptions if finally throws an exception, but could prevent unexpected bubbling up of errors?
You can use both the ways of writing try,catch and finally and it varies from situation to situation.
Consider the following code listing for try...except inside try...finally.
//You will receive a DataSet is some state.
try
try
//Here you'll change its state and perform operations on it.
//If some exception occurred you will handle it.
except
//Handle exception.
end;
finally
//Put the DataSet again in the same state.
end;
The above code listing shows the uses of try...except inside a try...finally block.
Consider the following code listing for try...finally inside try...except.
try
LObject:= TObject.Create;
//Create an Object. It better idea to create an object outside try..finally block.
//If some exception occured while creating an object an exception will be thrown.
//However its not a good idea to catch such an exception.Let the system handle it.
try
//Use the Object.
finally
//Free Object.
end;
// Returns True
except
// Returns False.
end;
Here the above code listing may be used in such a situation where the function return only true and false. If some exception occurred then simply set the value to false.
Suppose I have something like this :
try code_that_fails()
catch _:_ -> .....
How do I print the stacktrace in the catch block? That block catches all exceptions, but I don't know how to print the stack...
Can you help me?
From Erlang 21.0 onwards, there's a new official way to get the stack trace. An optional pattern match in the try expression on the third parameter in the exception, which will contain the stack trace:
try
code_that_fails()
catch
_:_:Stacktrace ->
erlang:display(Stacktrace)
end
Older versions (OTP 20 and below)
For versions of Erlang/OTP 20 and below, you need to use get_stacktrace/0, which allows you to get the stacktrace of the last exception in the calling process:
try
code_that_fails()
catch
_:_ ->
erlang:display(erlang:get_stacktrace())
end
An answer for your question is:
io:format("Backtrace ~p~n", [erlang:get_stacktrace()])
The current function is at the head of the list. Read more in man 3erl erlang or erlang:get_stacktrace/0
In your example, you don't need the try; you can just do
result = (catch code_that_fails()).
If an exception is raised, catch returns a tuple that contains the error code and stack trace.
Note that this is generally considered bad practice as it can mask exceptions. The stacktrace approach described in another answer is almost certainly what you want.
try is an extension of the original catch functionality; if you use it, you need to specify clauses for each exception type you would like to catch, and handle them appropriately. See sections 6.18/6.19 of the Erlang reference manual for details and clear examples.