Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.
The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks:
The try operator. It opens a new try-catch-block.
The catch(<exception_type>, ) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the . If at the given moment there is no open try-catch-block, then we can't use the catch operator.
The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.
Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".
To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.
Your task is: given a program in VPL, determine, what message will be displayed on the screen.
Input
The first line contains a single integer: n (1 ≤ n ≤ 105) the number of lines in the program. Next n lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces.
The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark.
The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols.
Length of any line in the input file does not exceed 50 symbols.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Print the message the screen will show after the given program is executed.
Examples
Input
8
try
try
throw ( AE )
catch ( BE, "BE in line 3")
code
try
catch(AE, "AE in line 5")
catch(AE,"AE somewhere")
Output
AE somewhere
Input
8
try
try
throw ( AE )
catch ( AE, "AE in line 3")
code
try
catch(BE, "BE in line 5")
catch(AE,"AE somewhere")
Output
AE in line 3
Input
8
try
try
throw ( CE )
catch ( BE, "BE in line 3")
code
try
catch(AE, "AE in line 5")
catch(AE,"AE somewhere")
Output
Unhandled Exception
Note
In the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE.
In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere")
In the third sample there is no blocks that can be activated by an exception of type CE.
We need to simulate the exception handling mechanism described. The program consists of lines with operators try, catch(<exception_type>, ""), and throw(<exception_type>). The program is correct: each try is matched with a later catch, nesting is proper. Exactly one throw operator.
We need to determine which catch block (if any) catches the thrown exception. The rule: Among try-catch-blocks such that:
try occurs earlier than the throw.
catch occurs later than the throw.
The catch's exception type matches the thrown type (exact string match).
If multiple such blocks, choose the one whose catch occurs earliest (i.e., earliest after the throw). Actually: "the system activates the block whose catch operator occurs earlier than others." So among all candidate blocks, pick the one with minimal position (line number) of the catch operator? But careful: The catch operator must be later than the throw. So among those that satisfy, choose the one with the smallest index (position) of its catch operator. That is the earliest catch after the throw. Also, these blocks are nested? The rule is that they are try-catch blocks that are open? Actually the description: "a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others." So it's not about which block is innermost, but simply which catch appears first after the throw among those blocks whose try is before the throw and type matches. It does not consider the nesting? However, the typical try-catch semantics would consider the innermost block that can catch, but here they specify something else: it looks at all blocks that have try before throw and catch after throw, regardless of nesting, and picks the earliest catch. But we should examine the examples to confirm.
Example 1:
Program lines (with line numbers approx):
1: try
2: try
3: throw ( AE )
4: catch ( BE, "BE in line 3")
5: try
6: catch(AE, "AE in line 5")
7: catch(AE,"AE somewhere")
Now the throw is at line 3.
Which blocks have try before line 3 and catch after line 3 and type AE?
Block1: try at line1, catch at line7 (type AE) -> yes
Block2: try at line2, catch at line4 (type BE) -> type mismatch
Block3: try at line5? but try at line5 is after throw, so not before -> not considered.
Block? There's also a block: try at line1? Actually there are two try-catch blocks: outer: try line1, catch line7; inner: try line2, catch line4; and another: try line5, catch line6. However, the inner try line2, catch line4: try before throw? line2 <3, catch after? line4>3, yes but type BE mismatch. So only outer block qualifies. Also note that the block try line5, catch line6: try not before throw (line5>3) so not considered.
So only one candidate -> output: "AE somewhere". matches.
Example2:
Lines:
1 try
2 try
3 throw(AE)
4 catch(AE,"AE in line 3")
5 try
6 catch(BE,"BE in line 5")
7 catch(AE,"AE somewhere")
Now throw at line3.
Candidates: try line1 catch line7 (AE, yes), try line2 catch line4 (AE, yes). Both have try before (1,2) and catch after (7,4). Among these, which catch occurs earlier? line4 is earlier than line7, so choose catch at line4. Output "AE in line 3". That matches.
Thus the rule: among blocks with try before throw and catch after throw and matching type, choose the one with the smallest catch line number.
But wait: what about nesting? Could there be a block where the catch is after throw but the try is before, but the block is not actually active because it's already closed? Actually, in programming languages, once a catch is encountered, the block is closed. But the rule here is just based on positions, not dynamic state. The problem says: "the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block." So the program is syntactically correct: it's a sequence of try and catch that is well-balanced (like parentheses). The dynamic execution: we execute the program line by line. When we encounter try, we push onto a stack? Actually the semantics described: try opens a block, catch closes the most recent open try. So the dynamic execution would process lines sequentially, and when a throw occurs, we need to find a suitable catch among currently open try blocks? But the problem description gives different rule: it says "a try-catch-block is activated, such that this block's try operator was described earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator." It doesn't mention the dynamic stack of open blocks at the time of throw. It just says the block's try is before throw and catch is after throw. That seems to ignore whether the block is still open at the time of throw? In typical exception handling, only the blocks that are currently active (i.e., whose try has been entered but not yet exited) can catch an exception. But here they define it based on textual order: try before throw, catch after throw, regardless of whether the catch is after the throw in the code and if the try is still open? However, if a try block is closed before the throw, then its catch would be before the throw, so the condition catch after throw would fail. So only blocks whose catch is after throw could be considered. But what about blocks that are nested and the inner block's catch is after throw but its try is before throw? That would be active if the inner try is before throw and not yet closed at throw? In typical semantics, when a throw occurs, you look at the most recent try block that is not yet closed. That's essentially the innermost open try. But the rule in this problem is not exactly that: they say "If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others." In example 2, both outer and inner blocks are open at the time of throw? Let's examine dynamic execution: line1 try (push outer), line2 try (push inner), line3 throw. At this point, the stack has two open tries: inner (most recent) and outer. Which catch will handle? Typically innermost would catch if its catch type matches. The inner catch is at line4, which is after throw (dynamic: after throw, the exception is thrown, control jumps to catch. In typical languages, the catch of the same block is after the try body, which includes the throw. So yes, inner catch is after throw in code order. So both inner and outer have try before throw and catch after throw. But in typical semantics, the inner catches because it's the most recent on the stack. However, this problem says we choose the one whose catch occurs earlier. In example 2, the inner catch is earlier (line4) than outer catch (line7). So that matches the typical innermost because inner catch usually appears earlier in code (if nested properly)? Actually in nested try-catch, the inner catch is typically before the outer catch. So the "catch occurs earlier" might correspond to innermost? But wait, what about scenario where there are multiple blocks at the same level? For example, try block A, then later try block B, but B is not nested in A? Actually the program is a sequence of operators; try and catch can be nested. The structure is like parentheses: a try is followed by some code (which may include tries and catches) and then its matching catch. So the blocks are properly nested. For a throw inside some nested structure, the set of blocks that have try before throw and catch after throw are exactly those that are currently open (i.e., whose try has been encountered but whose catch has not yet been encountered) and also any block that encloses the throw? Actually, for a block to be "open" at throw, its try must be before throw and its catch must be after throw. That's exactly the condition. So the set of blocks satisfying the condition is precisely the set of blocks that are currently active (i.e., not yet closed) at the moment of throw. Because for a block to be active, its try has been executed (so before throw) and its catch hasn't been executed yet (so after throw). So indeed, the condition matches the set of currently active try-catch blocks. So we are selecting among the currently active blocks. The typical semantics would choose the most recent (the one whose try was most recently encountered) i.e., the innermost. But here the rule is: choose the one whose catch operator occurs earlier. In properly nested blocks, the innermost block's catch appears earlier than the outer ones because it is closed first. For a given throw inside nested blocks, the inner block's catch is textually before the outer block's catch. So the "earliest catch" corresponds to the innermost block. Let's confirm: If you have nested tries:
try { // line1
try { // line2
throw; // line3
} catch(...) { // line4
}
} catch(...) { // line5
}
The inner catch at line4 is earlier than outer catch at line5. So earliest catch = innermost. But what about overlapping but not nested blocks? Overlapping blocks are not possible because of proper nesting: try-catch blocks must be nested like parentheses. So the structure is a tree. For a throw inside some block, the active blocks are those on the path from the root to the current position. Their catches are ordered such that the deeper the block, the earlier its catch appears (since inner block must be closed before outer). So earliest catch corresponds to the innermost active block. So the rule is effectively "innermost block". However, is there any scenario where earliest catch does not correspond to innermost? Suppose two blocks are not nested but one after another? But then they cannot both be active because after the first block is closed, the second hasn't started yet. For both to be active, they must be nested. So indeed, among active blocks, the earliest catch is the innermost. So the rule is equivalent to the typical "most recent try". So we could just simulate a stack of active try blocks, and when throw occurs, we look for the topmost (most recent) try that has a matching catch type? Wait, we must consider the catch type: Only blocks whose catch has the matching exception type can be activated. The rule says: among blocks that satisfy (try before throw, catch after throw, and type matches), choose the one with earliest catch. That is the innermost among those with matching type. But note that the innermost active block might not have matching type; then we need to go outward. However, the rule as stated: If there are several such blocks, choose the one with earliest catch. That means if multiple active blocks have matching type, we pick the one with smallest catch line number. Since the innermost active block has the smallest catch line number among active blocks (because of nesting), it would be selected. But what if there are multiple active blocks with matching type, but the innermost does not have matching type? Then the set of blocks with matching type are only the outer ones. Among those, the one with earliest catch is the one that is the innermost among those with matching type, because catch line numbers increase as you go outward. So that matches: we need to find the innermost active block whose catch type matches. So we can simulate by maintaining a stack of try-catch blocks (when we encounter try, push a placeholder; when we encounter catch, pop the most recent try and record its catch type and message, and also store its catch line number). However, at the moment of throw, we need to know which try-catch blocks are currently active, and among them, find the one (innermost) whose catch type matches the thrown type. The catch type and message are associated with the catch operator, which occurs after the throw in code order, so at the time of throw we haven't seen the catch yet. So we cannot know the catch type until we read the catch? But the program is given entirely; we can pre-process to know for each try which catch (type, message) will close it. Since the program is correct, each try is matched with a unique catch. We can parse the entire program, building a stack to match tries with catches, and record for each try the associated catch's type, message, and line number of the catch. Then we can find all active tries at the throw point: those tries that have been encountered before throw and whose catch occurs after throw. This is essentially the stack of tries at the moment just before executing the throw (i.e., after processing all operators before the throw). So we can simulate execution: iterate through lines, maintain a stack of indices of try operations (like line numbers) that have been entered but not yet closed. When we see a try, push its line number (or an identifier) onto the stack. When we see a catch, pop the top try, and record for that try: the catch line number, type, message. Also we might need to store this mapping so that when we later encounter a throw, we can inspect the current stack.
Important: The throw occurs at some line. At that moment, the stack contains tries that have been entered and not yet closed. For each such try, we know its corresponding catch (since we have parsed the entire program, we could pre-compute the mapping from try line to its catch info). But at the moment of throw, we haven't seen the catches that are after the throw yet, but we can pre-compute the mapping by a first pass: we need to know for each try, what is its catch line, type, message. However, to know that, we need to parse the entire program: as we read lines, we can match tries with catches using a stack: when we encounter a try, push its index; when we encounter a catch, pop the top try index and store the catch info for that try. So we can do this in one pass, storing all lines in an array? Since n up to 1e5, storing lines is fine. But we need to know the throw line and type. Also we need to be careful: The catch operator lines may contain spaces; we need to parse the type and message. Also we need to handle empty lines and lines with only spaces: they contain no operator, so we skip? The problem says each line contains no more than one operator, but can contain empty lines or lines with only spaces. So we must treat lines that have no operator as nothing; they do not affect the program semantics. So we need to parse each line to see if it contains a try, catch, or throw. Also, there may be spaces before/after. So we can strip leading/trailing spaces. Then check if the line starts with "try", or "catch", or "throw". Note: "catch" or "throw" include parentheses. So we can detect.
Strategy:
Read n, then read n lines (preserving them as strings). We'll store them in an array lines for potential later use? Actually we need to parse operators. Since we need to process in order to match tries with catches, we also need to know the line numbers (1-indexed as per input order). But empty lines still count as lines? The input lines are numbered from 1 to n. However, the semantics of "operators" are only on lines that contain them. Empty lines or spaces-only lines contain no operator, so they are ignored in execution. But they still occupy line numbers; do they affect the ordering? The throw operator appears on some line; its position relative to other operators is determined by line numbers (since the description says "try operator was described earlier than the used throw operator" meaning earlier in the program text, so line numbers order matters). Even if there are blank lines, the order of lines is still the order of the source code. So we need to consider the line indices. However, when we talk about "catch operator occurs earlier", we compare line numbers. So we need to map each operator to its line number (index in input). And blank lines are irrelevant but still count for line numbering. So we can just iterate through lines from 1 to n, parse each line to see if it contains an operator. If it does, we process it. So we will treat line numbers as indices. We'll maintain a list of operators in order with their line numbers. But easier: during reading, we can process sequentially, maintaining a current line number. For each line, after stripping leading/trailing spaces, if it's empty (or length 0), we skip (no operator). Else we parse the first word to determine operator.
However, note: There could be lines with only spaces that after stripping become empty; they contain no operator. Also there could be lines with try/catch/throw preceded by spaces; after stripping, they start with the keyword.
Thus we can do a single pass: iterate i from 1 to n, read line s. Strip leading/trailing spaces. If s == "" (or after stripping, length 0), continue (skip, no operator). Else if s starts with "try": it's a try operator. The line may be just "try" or "try " with spaces but after stripping it's "try". So if s == "try" (maybe with spaces? Actually after stripping, it should be exactly "try" but could have spaces after? For safety, we can check if the first non-space characters are "try" and then maybe nothing or spaces, but the problem says the operator is either try, catch, or throw. For try, it's simply the word "try". So we can check if s == "try". But might there be spaces between? after stripping, it should be exactly "try". So we can do if s.startswith("try") and s.strip() == "try". So safe.
If it's catch: s starts with "catch". We need to parse the parameters: catch ( , "" ). The format: "catch" followed by parentheses with two arguments separated by comma. The message is in double quotes. We need to extract the exception type and the message (without quotes). There may be spaces before/after parentheses, before/after comma, etc. So we should parse after the opening parenthesis. Approach: find the first '(' and last ')' (or just parse). Since constraints small (line length ≤50), we can do simple string manipulation. We'll locate the parentheses, extract substring inside, split by comma (but careful: message contains quoted string which might contain spaces, but no commas inside because message only contains letters, digits, spaces). So we can split at the comma that is outside quotes. But easier: we can use regex or manual parsing: find the first '(' and then find the comma that is not inside quotes. Since quotes appear only around message, and message does not contain quotes or commas, we can simply find the first comma after the '(' and before the ')'. But there might be spaces. So we can: after stripping, we have something like "catch ( AE , "AE in line 3" )". We can remove the prefix "catch" and then the rest is parentheses part. We can get the substring after '(' up to but not including ')'. Then split by ','? But if message contains spaces, it's okay. But the message is in quotes; we need to extract the string inside quotes without the quotes. However, we need the type and the message as separate strings. So we can: locate the opening '(' and closing ')'. Then inside, trim spaces, then find the first comma. Left part before comma is type (trim). Right part after comma is message part (trim). The message part will be in double quotes, possibly with leading/trailing spaces. We need to remove the double quotes. So we can strip and then remove first and last character if they are '"'. Or use string methods.
If it's throw: similarly, extract the exception type. Throw format: throw(<exception_type>) or throw ( AE ) with spaces. So parse similarly.
We need to store the following:
For each try: we need to later know its associated catch info. So we will maintain a stack of try indices (say try_line_numbers). When we encounter a try, we push its line number i onto the stack. Also we could allocate an object for that try to store its catch info (type, message, catch_line) later.
When we encounter a catch: it closes the most recent try on the stack. Pop the try index t from the stack. Record for that try: catch line number = i, exception_type = parsed type, message = parsed message.
When we encounter a throw: we need to record its line number (throw_line) and thrown type. Since exactly one throw, we can store it.
After processing all lines, we have:
Mapping from try line number to catch info (type, message, catch_line).
The throw line and throw type.
Now we need to determine which catch handles it. According to semantics, the active tries at the moment of throw are those tries that have been encountered before the throw and whose catch is after the throw. But note: In the dynamic execution, when we encounter the throw, we haven't executed any catch that appears after the throw. However, some tries might have been closed before the throw (i.e., their catch lines are before the throw). Those are not active. The active tries are exactly the ones on the stack at the moment we process the throw. But we can compute the stack state just before the throw by simulating again, or we can use the mapping and throw line to determine which tries are active: A try is active at line throw_line if:
try_line < throw_line (try encountered before throw)
catch_line > throw_line (catch not yet encountered, i.e., still open)
Because the program execution goes sequentially; if catch_line is before throw_line, then that catch would have been executed before the throw, closing the try, so that try is not active. So condition: try_line < throw_line < catch_line.
But also, the try must be properly nested; the condition that try_line < throw_line < catch_line essentially captures that the throw is inside the block (since the block's body is between try and catch). However, is it sufficient? Consider nested blocks: For a try that encloses the throw, its try_line < throw_line, and its catch_line > throw_line. For a try that is not enclosing (i.e., a sibling before), its catch_line would be before throw_line because its block ends before the throw. So yes, the set of tries with try_line < throw_line < catch_line are exactly the tries whose blocks contain the throw (i.e., the active stack). This is due to proper nesting: if you have nested tries, the inner try has try_line greater than outer's try_line, and catch_line less than outer's catch_line. So for a given throw_line, the tries that satisfy this inequality are those on the path from the outermost containing block to the innermost containing block. So we can compute active tries by scanning all tries and checking this condition.
But we need to find the innermost among those that have matching type. The innermost would be the try with the largest try_line? Or the one with the smallest catch_line? Since nested blocks have try_line increasing with depth and catch_line decreasing with depth? Actually, for nested blocks: outer try at line a, catch at line d; inner try at line b (b > a), catch at line c (c < d). For a throw at line t such that a < t < d and b < t < c. So among active tries, the innermost has the largest try_line (most recent) and the smallest catch_line (since it closes earlier). So we could either pick the one with maximum try_line or minimum catch_line. Both give the innermost. However, the rule says choose earliest catch, i.e., minimum catch_line among those with matching type. That's equivalent to innermost among those with matching type. So we can implement:
Collect all tries that satisfy: try_line < throw_line < catch_line, and catch_type == throw_type.
If none, output "Unhandled Exception".
Else, among them, choose the one with minimum catch_line (or maximum try_line). But careful: Could there be multiple tries with same catch_line? Not possible because catches are at distinct lines. So unique.
Alternatively, we can simulate the stack: While reading lines sequentially, we can process until we reach the throw, maintaining a stack of tries (their line numbers). When we encounter the throw, we have the current stack (list of try line numbers in order from outermost to innermost). Then we can examine the stack from innermost (top) to outermost, looking for the first (i.e., innermost) try whose catch_type matches the throw_type (using the mapping we have for catch info, which we might not have fully yet because we haven't processed catches after throw). However, we would need the catch info for those tries, but we haven't encountered the catches yet (they are after throw). But we could pre-parse the entire program to build the mapping before simulation. That is doable: we can first read all lines, parse all operators, match tries with catches, store the catch info for each try. Then we can simulate again (or use the computed conditions). Since n is up to 1e5, two passes are fine.
Simpler: Build the mapping in one pass, while also recording the throw info. But to match tries with catches, we need to know when we encounter a catch, which try it closes. That's a stack. So we need to process in order. So we can do:
Initialize:
stack = [] (stores indices of tries; we can store object with try_line number and maybe catch info later)
We'll also need to store catch info for each try. Since we only need catch info for tries that are active at throw (which may include those not yet closed at throw), but we need catch info for all tries? Actually we need catch info for any try that could be candidate, so we need to know the catch type for each try. So we need to map try_line -> catch_info. We'll fill this when we see catch.
During the pass:
For each line i from 1..n:
parse if operator.
if try: push i onto stack.
if catch: pop the top try index t = stack.pop(); parse type and message; store catch_info[t] = (type, message, i).
if throw: record throw_line = i; throw_type = parsed type; also note that after throw, we could stop processing? But we still need to finish parsing to match later tries and catches? Actually we need to match all tries with catches to know catch info for tries that are before throw (and maybe after?). But for tries that start after throw, we don't need their catch info because they cannot be active (try_line > throw_line). However, we still need to correctly parse the rest to maintain the stack? Since the program is correct, the remaining code will contain catches that close any open tries. But if we stop early, we won't have the catch info for those tries that started before throw and close after throw. Those are important because they are active at throw. So we need to parse the entire program to get their catch info. So we cannot stop at throw; we need to continue to process the rest to fill the mapping for those tries. So we must parse all lines.
Thus after first pass we have:
throw_line, throw_type.
mapping catch_info for every try (since each try gets a catch).
Also we have the stack should be empty at end; but we don't need to verify.
Now to find active tries: we need all tries t such that t < throw_line < catch_info[t].line (catch_line) and catch_info[t].type == throw_type.
But note: Some tries might have try_line < throw_line but catch_line also < throw_line; those are closed before throw, not active. So we need to filter.
We can iterate over all tries in mapping (keys are try_line numbers) and check conditions. However, number of tries could be up to n/2? So up to 1e5, fine.
But we also need to find the one with minimal catch_line among those satisfying conditions. That's straightforward.
Alternatively, we could simulate a second pass: go through lines until throw, pushing try indices onto a stack. At the moment we hit throw, we have the stack (the active tries). Then we could pop from the stack (starting from top) and check each try's catch type by looking up catch_info (which we have from first pass). The first (innermost) that matches is the handler. This would also work without scanning all tries. That might be more efficient but not necessary.
Given we already have mapping, we can compute active tries by scanning all try entries. But we need to know for each try, its catch_line. So we have that. So we can just filter.
But careful: Could there be tries that are not in the mapping? Actually every try should have a catch, so mapping covers all tries. So fine.
One nuance: In the first pass, when we encounter a catch, we pop the top try from the stack. This requires that we have processed the try earlier. Since program is correct, that holds. So the mapping from try_line to catch info is built correctly.
Now potential pitfalls: The input lines may contain only spaces or be empty. We must ignore them as they contain no operators. However, they still count for line numbers. The try_line, catch_line, throw_line are the line numbers in the input (1-indexed). The condition "try operator was described earlier than the used throw operator" means compare line numbers. So if throw_line is 5, and try_line is 5? No, earlier means strictly less, because throw can't be on the same line as try. So we use <.
But what if there is a try on the same line as throw? Not possible because each line contains at most one operator.
Thus we can proceed.
Edge Cases:
No active try with matching type -> Unhandled Exception.
There may be multiple active tries with matching type, but innermost (smallest catch_line) should be selected.
Now we need to parse messages: The message includes spaces, digits, letters, but also possibly surrounded by quotes. We need to output the message without quotes. So we extract.
Now consider parsing of catch lines: Example: catch ( BE, "BE in line 3") after stripping maybe catch ( BE, "BE in line 3")? We need to extract type BE and message BE in line 3. We can do:
Find the opening '(': idx1 = s.find('(')
Find the closing ')': idx2 = s.rfind(')') (since there may be spaces after but no nested parentheses)
Inside = s[idx1+1:idx2].strip()
Then find the first comma that is not inside quotes. Since message is quoted and does not contain commas or quotes, we can just split at the first comma in the string. But there might be spaces around comma. So we can do:
parts = inside.split(',', 1) # split at first comma
if len(parts) != 2: error but guaranteed correct.
type_str = parts[0].strip()
msg_part = parts[1].strip()
Then msg = msg_part[1:-1] if msg_part starts and ends with '"' else msg_part (but guaranteed quotes). So we can strip the surrounding quotes.
For throw: similar but only one argument: inside parentheses is the exception type. So we can extract similarly: s.find('('), s.rfind(')'), inside.strip().
Now we also need to handle lines that may have trailing comments? No.
Implementation plan:
Read n.
Initialize an empty list lines? Not needed; we process line by line.
For i in range(1, n+1):
s = input().strip() # but careful: after strip, we lose leading/trailing spaces; but if the line is only spaces, strip yields empty string. That's fine.
if s == "":
continue # no operator
if s == "try":
stack.append(i)
elif s.startswith("catch"):
# parse
# Must ensure that there is a try on stack.
# Find '(' and ')'
left = s.find('(')
right = s.rfind(')')
if left == -1 or right == -1:
# shouldn't happen
continue
inner = s[left+1:right].strip()
# split at first comma
comma = inner.find(',')
if comma == -1:
# should not happen
continue
exc_type = inner[:comma].strip()
msg_with_quotes = inner[comma+1:].strip()
# Remove quotes
if msg_with_quotes.startswith('"') and msg_with_quotes.endswith('"'):
msg = msg_with_quotes[1:-1]
else:
msg = msg_with_quotes # but should not happen
# pop try
if not stack:
# shouldn't
continue
t = stack.pop()
catch_info[t] = (exc_type, msg, i)
elif s.startswith("throw"):
# parse throw
left = s.find('(')
right = s.rfind(')')
if left != -1 and right != -1:
exc_type = s[left+1:right].strip()
throw_line = i
throw_type = exc_type
else:
# invalid
pass
else:
# unknown line? ignore? but program only contains these operators.
pass
After loop, we have mapping.
Now compute candidates:
candidates = []
for t_line, (c_type, msg, c_line) in catch_info.items():
if t_line < throw_line < c_line and c_type == throw_type:
candidates.append( (c_line, msg) ) # store catch_line and message
If candidates empty: print("Unhandled Exception")
else:
select the one with smallest c_line (since we want earliest catch)
best = min(candidates, key=lambda x: x[0])
print(best[1])
Testing with examples.
Example1:
Lines:
1: try
2: try
3: throw ( AE )
4: catch ( BE, "BE in line 3")
5: try
6: catch(AE, "AE in line 5")
7: catch(AE,"AE somewhere")
Processing:
i=1: try -> stack=[1]
i=2: try -> stack=[1,2]
i=3: throw -> throw_line=3, throw_type="AE"
i=4: catch -> parse: type="BE", msg="BE in line 3", pop t=2 -> catch_info[2]=("BE","BE in line 3",4)
i=5: try -> stack currently after pop: [1]; then push 5 -> stack=[1,5]
i=6: catch -> parse: type="AE", msg="AE in line 5", pop t=5 -> catch_info[5]=("AE","AE in line 5",6)
i=7: catch -> parse: type="AE", msg="AE somewhere", pop t=1 -> catch_info[1]=("AE","AE somewhere",7)
Now candidates:
t_line=1: c_type="AE", c_line=7 -> t_line=1<3<7 true and c_type==AE -> candidate (7, "AE somewhere")
t_line=2: c_type="BE" -> no
t_line=5: c_type="AE", c_line=6 -> t_line=5<3? false (5<3 false) -> not active (since try after throw)
So only candidate -> output "AE somewhere". correct.
Example2:
Similar mapping:
catch_info[2]=("AE","AE in line 3",4) (from try line2)
catch_info[5]=("BE","BE in line 5",6) (try line5)
catch_info[1]=("AE","AE somewhere",7)
throw_line=3, throw_type="AE".
Candidates:
t_line=1: (7, "AE somewhere") -> 1<3<7 true and type matches -> candidate (7)
t_line=2: (4, "AE in line 3") -> 2<3<4 true and type matches -> candidate (4)
t_line=5: false.
min c_line = 4 -> message "AE in line 3". correct.
Example3:
throw_type = "CE"
Candidates: check t_line=1 type AE -> no; t_line=2 type BE -> no; t_line=5 type AE -> no (and try after). So none -> "Unhandled Exception". correct.
Thus solution works.
But we must consider lines that are empty or only spaces: we skip them. However, does that affect line numbers? The condition uses line numbers in the original input file, not ignoring empty lines. For example, if there are empty lines, the throw might be at line 5, but the try could be at line 3, but line 4 empty. That's fine; the condition uses the actual line numbers. In our processing, we are using the actual line number i (1-indexed) as we read lines, and we only skip processing operators for empty lines. That's correct because the operator is absent on those lines. So try_line < throw_line still holds if try operator is on a line with a smaller number than throw, even if there are empty lines in between.
One more nuance: The problem says: "each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces." So an operator may be on a line with spaces before/after. Our strip removes leading/trailing spaces, but if the line has only spaces, it becomes empty and we skip. If it has operator, after stripping we get something like "try" or "catch(...)". That's fine. However, what about lines that contain only spaces but are not empty after stripping? Actually strip removes spaces, so they become empty. So skip.
Now, could there be lines that contain an operator but also spaces at start? After strip, it starts with the keyword. Good.
Now, parsing catch: we used s.find('(') and s.rfind(')'). But after stripping, the string might be "catch ( AE , "BE in line 3" )". That's fine. We don't need to remove the "catch" prefix, we just find parentheses in the whole string.
But what about lines where the operator is "catch" but there are no spaces before parentheses? e.g., "catch(AE, "AE in line 5")". Our method works: find '(' and ')'.
Now, need to handle that the message may contain spaces but no quotes or commas. The extraction of message by splitting at first comma works because the comma separates the type and the message; the message itself might contain spaces but not commas. So ok.
Now consider nested try-catch inside quotes? Not applicable.
Now check edge: what if the message contains double quotes? Not allowed; only letters, digits, spaces. So fine.
Now about performance: O(n) with small constant.
Now we must ensure we handle the case where the throw is before any catch? That's fine.
Now test with a simple case:
Input:
1
throw(AE)
Output should be "Unhandled Exception". Our mapping catch_info empty; candidates empty -> print "Unhandled Exception". correct.
Another:
3
try
throw(AE)
catch(AE,"message")
Mapping: try line1, catch line3. throw line2. Candidate: t_line=1, c_line=3, type matches -> candidate (3, "message") -> output "message". That's correct because the throw is inside the try block, catch after.
Now test nested where inner type mismatch but outer matches:
try (line1)
try (line2)
throw(AE) (line3)
catch(BE,"inner") (line4)
catch(AE,"outer") (line5)
Mapping: t2 -> catch4 (BE), t1 -> catch5 (AE). throw line3, type AE.
Candidates: t1 (1<3<5, type AE) -> candidate; t2 (2<3<4, type BE) no. So output "outer". But innermost (t2) does not match, so we go to outer. That's typical.
Now what about scenario where there are multiple blocks at same level? That can't happen because they would be sequential, not overlapping. For sequential blocks, if throw is inside second block, first block is already closed. So fine.
Thus algorithm is sound.
But there is a nuance: The condition "catch operator occurs earlier than others" means earliest in the program text, which is min catch_line. In nested scenario, innermost has earliest catch_line, but what if there are overlapping blocks that are not properly nested? But the program guarantees correctness, which likely includes proper nesting? The description: "The program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block." This implies proper nesting? Actually, if you have try, then try, then catch, then catch, that's nested. But could you have try, catch, try, catch? That's also valid: they are separate, not nested. That's still correct: each catch closes the most recent open try. So nesting can be flat as well. For example:
1 try
2 something (maybe throw)
3 catch(A,...)
4 try
5 catch(B,...)
This is fine. In such a structure, the tries are not nested; they are sequential. For a throw inside the second try (line4? Actually throw would be after try line4 and before catch line5), the active tries at that moment would be only the second try (since the first is already closed). So condition try_line < throw_line < catch_line holds only for the second try. So it's fine.
Now consider overlapping but not nested? That would be try1, try2, catch1, catch2: try1 before try2, catch1 after try2? That would be overlapping but not nested: try1, try2, catch1, catch2. Is that possible? Let's see: At try1, stack=[1]; try2 -> stack=[1,2]; then catch1 would close try2 (most recent), leaving stack=[1]; then catch2 closes try1. So the blocks are nested: try2 is inside try1? Actually try1 starts at line1, try2 at line2, catch1 at line3 (closes try2), catch2 at line4 (closes try1). This is nested: try2 is inside try1 because its catch is before try1's catch. So that's nested. So overlapping that is not nested would require try1, try2, catch2, catch1 (try2 closed after try1). That would be: try1, try2, catch2, catch1. At try1: stack=[1]; try2: stack=[1,2]; catch2: closes try2 -> stack=[1]; catch1: closes try1. That's also nested? Actually try1 encloses try2 because try2's catch is before try1's catch? Here try1's catch is after try2's catch, so try2 is still inside try1. So that's nested as well. In proper use of try-catch as a stack, any sequence of try and catch leads to a structure that is essentially a well-parenthesized sequence. So the blocks are either disjoint (if one closes before the next opens) or nested. They cannot partially overlap in a non-nested way because that would require closing an outer before inner, which is not allowed (since catch always closes the most recent open try). So indeed the blocks form a proper nesting structure. So the condition try_line < throw_line < catch_line exactly describes being inside the block.
Thus our method is correct.
Now, potential issues: Our parsing for catch and throw uses s.find('(') and s.rfind(')') on the stripped string. But what if the line is like "catch ( AE, "message" ) // comment"? The problem doesn't mention comments, so no.
Now, there is possibility of spaces inside the message? Yes, message can contain spaces, e.g., "AE in line 3". Our parsing using split at first comma and then stripping quotes works.
Now, we must be careful that the message may contain a comma? The problem says message consists only of upper and lower case english letters, digits and spaces. So no commas. So splitting at first comma is safe.
Now, what about throw with spaces: "throw ( AE )" -> after strip, it's "throw ( AE )". Our parsing: find '(' and ')', inside " AE " -> strip -> "AE". Good.
Now, after we have candidates, we pick min catch_line. But what about multiple candidates with same catch_line? Not possible.
Now, we need to output exactly the message without quotes.
Now, double-check: Could there be a catch whose message includes quotes? It says message is surrounded with quote marks. So we remove them.
Now, is there any scenario where a try block is active but its catch type matches but we should not consider it because the catch is before throw? Already excluded by condition.
Now, also note: The catch operator line might have spaces before the "catch" keyword. Our stripping removes leading spaces, so we start with "catch...". That's fine.
Now, one more nuance: The program may have multiple try-catch blocks, and the throw may be inside a try that is not closed because the catch is after. That's fine.
Now, verify with a test where throw is outside any try? For example, only throw. Then candidates empty -> Unhandled.
Now, test with nested try with same catch type, but inner catch after throw, outer catch also after throw: innermost will have smaller catch_line. So rule picks innermost, which matches typical semantics.
Thus algorithm is good.
But wait, the problem statement: "If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others." That is exactly what we did.
Now, we should consider if there is any subtlety about the definition of "described earlier" meaning the line numbers. Since we ignore empty lines, the line numbers still count. So our use of actual i is correct.
Now, potential issue: What about lines that contain only spaces? We skip them as no operator. But they still count as lines, so the line numbers i we use are the actual positions. Good.
Now, what about lines that contain an operator but also spaces before and after? We stripped, but we still use original i. That's fine.
Now, we must ensure we correctly parse when the line has extra spaces after parentheses, like "catch ( AE , "message" ) ". Our method works.
Now, what about when the catch message contains a double quote? Not allowed.
Now, we also need to consider that the program may have multiple try and catch but our mapping catch_info may not include tries that are closed after the throw? Actually it includes all tries.
Now, implement.
Complexity: O(n) time, O(number of tries) space (≤ n/2).
Edge Cases: n up to 1e5, line length up to 50, so string operations cheap.
Now, double-check parsing: For catch, we used s.find('(') and s.rfind(')'). However, if there are spaces between catch and '(', e.g., "catch (AE, "msg")", find('(') returns index of '(' in stripped string. Since we stripped leading/trailing spaces, the string begins with "catch", so '(' is after "catch". That's fine. But what if the line is "catch(AE, "msg")"? After stripping, it's "catch(AE, "msg")", find('(') works. So ok.
Now, for throw: similar.
Now, but we also need to consider that the keyword could be "try" with trailing spaces? After stripping, it becomes "try". So fine.
Now, we should also handle the case where after stripping, the line starts with "try", but there might be something else? It should be exactly "try" because it's a single operator. So we can check if s == "try". But what about "try " (with trailing space)? strip removes trailing spaces, so "try". So fine.
Similarly, for "catch" we can check if s.startswith("catch").
Now, note: There may be lines with only "try" and some spaces, but after stripping it's "try". So good.
Now, implement in Python.
Pseudo:
def solve():
import sys
data = sys.stdin.read().splitlines()
# First line is n
n = int(data[0].strip())
lines = data[1:] # but may have less if n lines after? Actually the input has exactly n lines after first. But read all lines and take first n lines after first.
# Ensure we have exactly n lines; if there are extra (like trailing newline) we take first n.
# But it's safer to iterate using index.
# We'll use an index pointer.
But reading with sys.stdin.readlines() might be easier.
Better:
def main():
import sys
input = sys.stdin.readline
n = int(input().strip())
stack = []
catch_info = {}
throw_line = None
throw_type = None
for i in range(1, n+1):
line = input().rstrip('\n') # keep spaces? we strip later for operator detection, but we need to keep to parse? Actually we can just work with the line as is. For detecting empty/only spaces, we can strip.
stripped = line.strip()
if not stripped: # empty or only spaces
continue
if stripped == "try":
stack.append(i)
elif stripped.startswith("catch"):
# parse
s = stripped
left = s.find('(')
right = s.rfind(')')
if left == -1 or right == -1:
# should not happen
continue
inner = s[left+1:right].strip()
# split at first comma
comma = inner.find(',')
if comma == -1:
continue
exc_type = inner[:comma].strip()
msg_part = inner[comma+1:].strip()
if msg_part.startswith('"') and msg_part.endswith('"'):
msg = msg_part[1:-1]
else:
msg = msg_part # fallback
# pop try
if not stack:
# error but ignore
continue
t = stack.pop()
catch_info[t] = (exc_type, msg, i)
elif stripped.startswith("throw"):
s = stripped
left = s.find('(')
right = s.rfind(')')
if left != -1 and right != -1:
exc_type = s[left+1:right].strip()
throw_line = i
throw_type = exc_type
# note: we don't break; continue to parse rest
# else ignore? not possible
code
# After parsing
if throw_line is None:
# no throw? but problem says exactly one
print("Unhandled Exception")
return
candidates = []
for t_line, (c_type, msg, c_line) in catch_info.items():
if t_line < throw_line < c_line and c_type == throw_type:
candidates.append((c_line, msg))
if not candidates:
print("Unhandled Exception")
else:
best = min(candidates, key=lambda x: x[0])
print(best[1])
Now test with examples.
But we must be careful: Our parsing of catch and throw uses stripped string, which removed leading/trailing spaces. However, what if the line has spaces inside the parentheses that affect splitting? e.g., "catch ( BE , "BE in line 3" )" - our inner splitting works because we strip inner and then find first comma. The comma might have spaces before or after, but we find the comma index correctly. So fine.
Now, one more nuance: The message could be empty? The problem says nonempty, so at least one char.
Now, about the catch_info: We store for each try its catch info. But what about tries that start after the throw? Their try_line > throw_line, but they are not active because try_line < throw_line fails. So they won't be candidates.
Now, think about scenario where there is a try before throw, but its catch is after throw, but the catch type matches, but the try is not the innermost among matching? Our candidate selection via min catch_line picks the innermost among matches.
Now, is there any scenario where multiple candidates have the same catch_line? That would require two different catches on same line, impossible.
Thus solution is fine.
But one more nuance: The problem says "the screen displays the ." If a block is activated, the message is displayed. Then does the program continue? Not relevant, we only need the message.
Now, confirm with a more complex example: Suppose multiple active blocks with matching type, but the innermost does not match, while two outer ones match? For instance:
try (type A) at line1
try (type B) at line2
try (type C) at line3
throw(A)
catch(C, ...) at line4? Actually type C catch, but throw type A -> not match
catch(B, ...) at line5? type B -> not match
catch(A, ...) at line6
Now active tries: line1, line2, line3. Only line1 catch type A matches. So candidate only line1. Output message from line6. That's correct.
Now, if both outer and inner match? For example:
try (type A) line1
try (type A) line2
throw(A)
catch(A, inner) line3
catch(A, outer) line4
Active tries: line1 and line2. Both match. Candidates: (catch_line3, inner) and (catch_line4, outer). Min catch_line = 3, so inner. That's innermost. So correct.
Now, what if there are two overlapping blocks but not nested? Not possible.
Thus algorithm stands.
Now, we need to be careful about reading input: The input may contain blank lines with spaces, we skip them. But note: The line count n includes those blank lines. Our iteration i from 1 to n goes over each line as provided; we skip only when stripped is empty. That's correct because blank lines contain no operator.
Now, the program could have lines that contain only spaces and also a comment? Not allowed. So fine.
Now, what about lines that contain "try" with leading spaces? after strip, "try".
Now, but what about lines that contain "try" but also something else like "try // something"? Not allowed.
Thus implementation should be fine.
Potential pitfalls:
In parsing catch, we use s.find('(') and s.rfind(')'). However, if the message contains parentheses? Not allowed, only letters, digits, spaces. So no parentheses inside message. So the last ')' is the closing parenthesis of the catch. So safe.
In throw, similar.
For catch, after extracting inner, we split at first comma. But what if the message string contains a comma? Not allowed. So safe.
Now, could there be a catch with no spaces after comma? e.g., "catch(AE,"message")". Then inner = "AE,"message"", split at first comma gives "AE" and ""message""? Actually inner after strip would be 'AE,"message"', split at ',' gives ['AE', '"message"']. That's fine.
Then msg_part is '"message"'. Remove quotes yields "message". Good.
Now, consider that the message might have escaped quotes? Not mentioned.
Now, output: just print the message string.
Now, confirm with examples.
Now, what about memory: catch_info dict can hold up to 5e4 entries (since each try has a catch). That's fine.
Now, think about the possibility of the throw being inside a try that has a catch that appears before the throw? That would be impossible because then the try would be closed before the throw, so the throw would be after the catch, which is after the try block; but if the throw is after the catch, it's not inside the try. So condition fails.
Thus algorithm correct.
Now, we should also consider that the program could have multiple throws? Problem states exactly one throw. So fine.
Now, we should consider if there is any scenario where the catch type matches but the catch line is after throw, but the try is not active because the catch is before throw? No.
Now, verify with a scenario where the try is before throw, catch after throw, but the try is not actually open because of some dynamic? Actually, because of sequential execution, the try is opened when execution reaches its line. At the time of throw, if the try line is before throw, it will have been opened. The only way it could not be open is if it was already closed by a catch before the throw. That would mean its catch line is before throw. So condition catch_line > throw_line ensures it's still open. So correct.
Thus the solution is correct.
Now, final code with proper handling of input reading and possibly large input.
We'll use sys.stdin.readline.
Potential bug: The input line may contain trailing newline; we rstrip it. But we also need to preserve spaces inside the line for parsing? We strip the whole line to check for emptiness and operator type. But for parsing catch, we use the stripped version. That's fine because all meaningful characters are preserved, and spaces at ends are irrelevant. But could there be a scenario where the message contains leading/trailing spaces? The message is surrounded by quotes, and within quotes there could be spaces. Removing spaces from the whole line might remove spaces that are outside quotes? But we strip the whole line before parsing. For example: " catch ( AE , " message " ) " after stripping becomes "catch ( AE , " message " )". The spaces inside the quotes remain. That's fine. The only potential issue: If the line starts with spaces, we remove them. That's okay because the operator is still identifiable.
Now, what about the case where the line has spaces after the closing quote but before the closing parentheses? Our stripping removes trailing spaces after the closing ')', which is fine.
Now, ensure we correctly handle the case where the message has leading/trailing spaces inside quotes. For example, message = " hello ". The quotes contain spaces. Our parsing: after splitting, msg_part = '" hello "'. Then we remove the surrounding quotes, yielding " hello ". That's correct. So the message with spaces will be printed as is.
Now, one more nuance: The problem says "Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed." So we must output the message exactly as inside quotes, preserving spaces. Our extraction does that.
Now, also note: The exception type is a string of letters only; no spaces. So our parsing for exception type is straightforward.
Now, final code. We'll implement solve() and call it.
Potential edge: Input might have n lines, but there could be extra blank lines after? The input specification says next n lines contain the program, but there may be trailing newline after those n lines. When using readline in a loop, we'll read exactly n lines. That's fine.
Now, we should also consider the case where the throw appears before any try? candidates empty -> unhandled.
Now, also consider the case where there is a try and catch but throw is between them, but the catch type mismatch. Then output unhandled.
Now, test with sample inputs.
We'll run mental:
Input sample1:
n=8
lines as described. Our parsing: Works.
Now, possible bug: In the first pass, we treat lines that are empty (after strip) as no operator. But we also need to ensure that the stack for tries/catches is maintained correctly. Since those lines have no effect, skipping them is fine. However, line numbers i still increment. That's correct.
Now, one more nuance: The program may have try and catch on the same line? It says each line contains no more than one operator, so not.
Now, verify with a case where there are multiple catches after throw but before the matching catch? Actually that's part of nesting.
Now, we must ensure that when we parse catch, we pop the correct try from stack. Since we are skipping empty lines, the stack corresponds to the order of tries encountered (not counting empty lines). That's correct because empty lines have no effect.
Now, one tricky part: The program might have try and catch operators interleaved with empty lines, but that doesn't affect.
Now, are there any lines that contain only spaces but after stripping become empty? Yes, we skip.
Now, but what about lines that contain only spaces but also a try? No, try would be non-space.
Thus fine.
Now, we need to consider that the input might contain lines with leading/trailing spaces that include the operator. After stripping, we get the operator string, but we lose distinction of original line number? We keep i, so fine.
Now, final implementation.
We'll write the code accordingly.
But wait, there is a nuance: In the problem, they say: "The catch(<exception_type>, ) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>." So the catch operator itself carries the type and message. In our mapping, we stored that.
Now, when we evaluate candidates, we used catch_info[t] which includes type and message. That's correct.
Now, but what about the scenario where the throw occurs inside a try block that has a catch with matching type, but there is an inner try block that also has a catch with matching type; we should catch at the inner one. That is achieved by picking smallest catch_line.
Now, could there be a scenario where the inner block's catch_line is actually larger than outer? No, because inner block closes earlier, so its catch_line is smaller. So smallest catch_line corresponds to innermost.
Thus correct.
Now, we should be careful: The condition "catch occurs earlier than others" refers to the position in the program, not necessarily the smallest catch_line? That is exactly smallest line number.
Now, let's think about the possibility of a try block that starts after the throw but its catch appears before the throw? Not possible because if try after throw, its catch after try > try > throw? Actually try after throw, then catch after try, so catch > try > throw, so catch after throw. But the try is not before throw, so not active. So ignore.
Now, could there be a try before throw, but its catch also before throw? That try is closed, not active.
Now, thus algorithm.
Now, implement.
But there is a nuance: We must consider that the throw might be inside a catch block? The program consists of try, catch, throw operators. Can a throw be inside a catch block? In typical languages, yes, but the problem description doesn't forbid it. The program is a sequence of operators; a catch operator closes a try, but after a catch, the program continues. The catch block might contain other operators, including throws. In the description: "The catch(<exception_type>, ) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the ." So the catch operator is executed only when an exception is thrown and it's activated. But in the program text, the catch is a line; after it, there can be further code. So it's possible to have a throw after a catch (i.e., after the catch line) but still within some outer try? That's allowed. But for our single throw, it's somewhere. And we need to determine which catch handles it.
If a throw occurs inside a catch block of some outer try, then at that moment, what are the active try blocks? The catch block is executed after an exception is caught, but that's after the activation. However, our problem only has one throw, so we don't have nested exceptions. But still, the throw could be placed after a catch line, within the scope of an outer try that is still open. For example:
try (line1)
try (line2)
catch(AE, "inner") (line3) // closes try line2
throw(AE) (line4) // this throw is after catch, but still inside outer try? Actually outer try started at line1 is still open because its catch hasn't been encountered yet (line5 maybe). So the active tries at throw line4: only outer try (line1) if its catch line is after line4. So candidate is outer catch if type matches. That's fine.
Our method using condition try_line < throw_line < catch_line will capture outer try if catch_line > line4. And inner try has catch_line = line3 which is less than throw_line (line4), so not active. So correct.
Now, what about a throw that occurs inside a catch block that is itself the catch of an active try? That would be after the catch is executed, but the catch block is not a try-catch-block; it's just code after the catch operator. The catch operator is a line that when executed (if activated) displays the message, but if it's not activated (i.e., we are just parsing the program), it's just a line? Wait, the semantics: The program is a sequence of operators. When we run the program, we execute operators in order. try opens a block. catch closes the most recent try and also defines the handler. But the catch operator is executed only when an exception is thrown and that block is activated? Actually, typical exception handling: The catch is not executed unless an exception is thrown. In the program text, the catch is part of the structure; it's not executed under normal flow. The problem description: "The catch(<exception_type>, ) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the ." So the catch operator has two roles: syntactically it closes the block, and semantically it defines the handler. In execution, if no exception, we just pass over the catch? Actually they say: "It closes the try-catch-block that was started last and haven't yet been closed." That implies that when we encounter a catch in the program flow (i.e., during normal execution), it simply closes the block (maybe without executing the handler). The handler is only executed if the block is activated by an exception. But then how does normal execution proceed after the catch? The description doesn't specify normal flow after catch. But the program is correct, and we only care about the single throw. So we don't need to simulate normal flow; we only need to determine which catch would be activated when the throw occurs. So the throw occurs at some line; we need to see which try-catch blocks are "active" (i.e., try has been executed, catch not yet) and whose catch type matches, and then pick based on earliest catch. This is independent of whether the catch operator would be executed later in normal flow; it's just about the block's definition.
Our method using static analysis of line numbers (try_line < throw_line < catch_line) correctly identifies blocks that are currently open at the throw.
Thus it's fine.
Now, test with a scenario where throw occurs inside a catch handler? But catch handler code is not represented explicitly; the catch operator just displays a message and presumably ends the block; but after that, there might be other operators. The throw could be after the catch operator but still inside the same block? Actually, after a catch, the block is closed. So the try-catch-block is closed. So any subsequent throw is outside that block. So fine.
Now, there is no explicit code for the body of catch; the catch operator itself is the handler. So the program after catch is not part of the handler; it's just subsequent code. So our static analysis is correct.
Now, we should double-check that our mapping catch_info is built correctly even if there are multiple catch operators after the throw that close tries that started before throw. That's needed for the candidates. Our first pass processes all lines, so we get those mappings.
Thus the algorithm is robust.
Now, we can write code.
We need to be careful about reading lines: Since n can be up to 1e5, using input() in a loop is fine. But we should use sys.stdin.readline for speed.
Potential pitfalls: Input lines may contain trailing spaces, we rstrip newline but not spaces? Actually rstrip('\n') will remove newline but keep trailing spaces. Then we call strip() which removes leading/trailing spaces, so we might remove spaces that are part of the line? But that's okay because we just need to detect presence of operator. However, for parsing, we use stripped string, which may have removed spaces that are meaningful? For the catch string, the spaces inside quotes are part of message; they are not stripped because strip() only removes leading/trailing spaces from the whole string, not inside. So fine.
But if we first rstrip('\n') then strip(), we remove trailing spaces. That's fine.
Alternatively, we could do line = input().rstrip('\n') and then stripped = line.strip().
Now, note: In Python, input() automatically strips newline. Actually input() returns the line without the newline. So we can just use input(). But it also removes trailing newline, not spaces. So after input(), we have the line as entered (including spaces). Then we can call s = line.strip() to get stripped version.
So:
for i in range(1, n+1):
line = input()
stripped = line.strip()
if not stripped:
continue
...
This works.
Now, we must be careful that input() may raise EOF if insufficient lines; but n lines are guaranteed.
Now, ensure we handle cases where the throw appears before we have processed its own try? That's fine.
Now, edge: When parsing catch, we pop from stack. But what if there are unmatched? Guarantee correct.
Now, one more nuance: The program may have nested try-catch blocks, and the throw might be inside a try that is not the most recent because of some intervening catches? Actually, if there is a try that is closed before the throw, it's not active. So stack at throw includes only those tries whose catch hasn't been encountered yet. That's what we capture via condition.
Now, about the mapping: When we encounter a catch, we pop the most recent try. However, the try that is popped might have started before throw and its catch after throw, which we need for candidate. We store it. So after whole parsing, we have info for all tries.
Now, to select candidate, we could also simulate the stack at throw: At the moment of throw, the stack contains tries that are currently open. But we don't have that stack directly because we processed the whole file. However, we could compute it by re-simulating up to throw, or we can compute via condition. Both fine.
But one more nuance: The condition try_line < throw_line < catch_line is necessary and sufficient for a try to be active? Is it always sufficient? Suppose we have try A at line 1, catch A at line 10. Inside it, there is try B at line 2, catch B at line 5. Throw at line 7. Then try A is active? try A: 1<7<10 true. try B: 2<7<5 false. So only A. That's correct because B is closed at line5. So works.
Now, what about a try that is opened after the throw? Not active.
Thus condition is correct.
Now, is there any scenario where a try is active but its catch_line > throw_line, but the try is not actually open because of some other reason? For example, if there is a catch that closes an outer try before the throw? That would mean catch_line < throw_line, so not satisfied. So fine.
Thus algorithm is good.
Now, we should also consider that the throw could be inside a try block that is itself not the innermost but still active, and we need to find innermost matching. Our candidate selection uses min catch_line among those with type match. That yields innermost.
Now, check: In nested scenario, the innermost active try has the smallest catch_line. So we choose that.
Now, confirm with an example where there are two matching blocks but the innermost catch_line is not the smallest? Actually innermost always has smallest catch_line because it closes first. So yes.
Thus code.
Now, we should also think about memory: catch_info may store all tries. That's fine.
Now, we should also consider if the program has multiple throw statements? Problem says exactly one. So fine.
Now, we need to output the message exactly. Not add newline? print adds newline by default, which is fine.
Now, finalize code.
But wait: There is a subtlety: The mapping catch_info built in first pass uses the pop order from stack. The stack is built while processing lines, skipping empty lines. This correctly matches try with its catch. However, what if there are empty lines between try and catch? That's fine; they are just lines with no operator, so we ignore them, but the line numbers still count. The stack still pushes try at its line number i, and when catch at line j is encountered, we pop the try that is most recent. That works because the empty lines don't affect the order.
Now, consider if there are multiple try on the same line? Not allowed.
Now, all good.
Now, we can write the code.
Potential improvements: Use regular expressions to parse, but not necessary.
Now, let's implement.
But also think about input lines that are like "try" with spaces at start: after strip, "try". Good.
Now, one more test: Input:
3
try
throw(AE)
catch(AE, " Hello ")
Output should be " Hello ". Our parsing: msg_part = '" Hello "' after strip? Actually inner after split: after comma, we get ' " Hello " ' .strip() yields '" Hello "'. Then remove quotes gives ' Hello '. So print " Hello ". That's correct.
Now, test with input where throw type contains spaces? No, exception type only letters, no spaces.
Now, edge: The message could be 20 symbols long; fine.
Now, we should consider the possibility that the throw line may have extra spaces like " throw ( AE ) " and after strip we have "throw ( AE )". Our parsing of parentheses works.
Now, code.
But wait: There is a nuance: In the catch parsing, we do s.find('(') and s.rfind(')'). If the catch line contains something like "catch(AE,"msg")//", but no comments. So fine.
Now, what about a catch line that has spaces inside the quotes? Already handled.
Now, maybe we should use a more robust parsing: Use regex to extract the content between parentheses, then split by comma outside quotes. But given constraints, simple is fine.
Now, I'll implement.
But let's also consider the possibility that the catch line may have more than one comma? Only two arguments: type and message, separated by one comma. So there should be exactly one comma. So splitting at first comma is correct.
Now, I think we're done.
Now, final code:
code
import sys
def main():
input = sys.stdin.readline
n_line = input()
if not n_line:
return
n = int(n_line.strip())
stack = []
catch_info = {}
throw_line = None
throw_type = None
for i in range(1, n+1):
line = input()
stripped = line.strip()
if not stripped:
continue
if stripped == "try":
stack.append(i)
elif stripped.startswith("catch"):
# parse catch
s = stripped
l = s.find('(')
r = s.rfind(')')
if l == -1 or r == -1:
continue # invalid, but should not happen
inner = s[l+1:r].strip()
comma = inner.find(',')
if comma == -1:
continue
exc = inner[:comma].strip()
msg_quoted = inner[comma+1:].strip()
if len(msg_quoted) >= 2 and msg_quoted[0] == '"' and msg_quoted[-1] == '"':
msg = msg_quoted[1:-1]
else:
msg = msg_quoted
if not stack:
continue
t = stack.pop()
catch_info[t] = (exc, msg, i)
elif stripped.startswith("throw"):
s = stripped
l = s.find('(')
r = s.rfind(')')
if l != -1 and r != -1:
exc = s[l+1:r].strip()
throw_line = i
throw_type = exc
# else ignore (shouldn't happen)
if throw_line is None:
print("Unhandled Exception")
return
best = None
best_catch_line = None
for t_line, (c_type, msg, c_line) in catch_info.items():
if t_line < throw_line < c_line and c_type == throw_type:
if best is None or c_line < best_catch_line:
best = msg
best_catch_line = c_line
if best is None:
print("Unhandled Exception")
else:
print(best)
if __name__ == "__main__":
main()
But wait: The mapping catch_info stores for each try line the catch info. However, we also need to consider that the try that is popped at catch might not be the one we think if we skip empty lines? Let's test with a scenario: There is a try on line 1, then an empty line (line 2), then a catch on line 3. Our code: i=1, stripped not empty, try -> stack=[1]; i=2, stripped empty -> continue; i=3, stripped catch -> pop 1, store catch_info[1] with line 3. So correct.
Now, what about a try that appears on a line with spaces? e.g., " try". After strip, it's "try". So we treat as try at line number i. That's correct.
Now, what about a catch that appears on a line with spaces before "catch"? After strip, it's "catch(...)". So good.
Now, what about a throw inside a try that has no matching catch? That would be incorrect program, but program is correct, so each try has a catch.
Now, potential problem: In the first pass, we need to ensure that the stack order matches the actual nesting. Since we skip empty lines, the order of operators is preserved. So good.
Now, consider a program with multiple tries and a throw after some catches. The stack at the time of throw should reflect only those tries that are still open. Our condition captures that.
Now, but we also need to consider that the throw may be inside a catch block that is part of a try that is already closed? That is fine.
Now, what about a try that starts before throw but its catch is after throw, but there is an intermediate catch that closes some other try? That's fine.
Now, test with a tricky example:
1 try
2 try
3 catch(A, "inner")
4 throw(A)
5 catch(A, "outer")
Line numbers: 1 try, 2 try, 3 catch (closes try 2), 4 throw, 5 catch (closes try 1). The active tries at throw: only try 1 because try 2 closed at line3. Condition: try1 (line1<4<5) true; try2 (line2<4<3 false). So only outer. So output "outer". That's correct.
Now, what if the throw type is something else: throw(B). Then no handler, unhandled.
Now, test:
1 try
2 try
3 catch(A, "inner")
4 throw(B)
5 catch(A, "outer")
Again only outer, but outer type A mismatch, so unhandled. That's correct.
Now, test with nested where inner type matches but catch line before throw? That can't be because throw inside inner would require catch after throw. So not.
Thus algorithm holds.
Now, one more nuance: The problem says "If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others." Our method picks the smallest catch_line among candidates. That's correct.
Now, consider the case where two different try blocks have the same catch_line? Impossible.
Now, we should also consider the scenario where the throw occurs exactly on a line that is a catch? Not possible because each line contains at most one operator, and throw is an operator; it can't be both catch and throw. So fine.
Now, final answer.
But we need to ensure that our parsing of catch does not mistakenly treat a line with "catch" as something else. Since we check startswith("catch"), it will also catch lines that start with "catch" but maybe it's "catchy"? Not in program.
Now, potential issue: In Python, string.find returns -1 if not found; we check.
Now, about reading input: There's a possibility that n lines may contain blank lines with spaces, and we skip them. That's fine. But we must ensure that we read exactly n lines. Using input() in a for loop will read n lines, even if some are empty. That's fine.
Now, final code with proper structure.
Now, let's run through the given examples manually.
Example1 input as above. Our code will output "AE somewhere". Good.
Example2 output "AE in line 3". Good.
Example3 output "Unhandled Exception". Good.
Now, I'm confident.
But there might be a hidden nuance: The program may contain spaces inside the parentheses that cause our inner extraction to include leading/trailing spaces, but we strip after extraction for type and msg_part. That's fine.
Now, about the message: Could it contain backslashes? Not allowed. So fine.
Now, final code.
But let's think about performance: n up to 1e5, each line parsing constant time. dict iteration up to number of tries (~5e4). So fine.
Now, I will produce final answer.
But before finalizing, let's re-read problem description for any subtlety: "The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.
Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception"."
It says "this block's catch operator is described later that the used throw operator." So catch must be after throw. That's what we use.
Now, the program is correct: each catch closes the most recent open try. So the mapping we built by stack is correct.
Now, we need to ensure that we treat try-catch-blocks that are not yet closed at the throw. Our condition ensures that.
Now, what about the possibility that the throw occurs inside a catch block that is part of a try that is still open? That catch block is not a try-catch-block; it's just an operator that closes a try. But after the catch, that try is closed. So the throw is not inside any block that starts with that try. So it's either inside outer tries. So our condition holds.
Now, think about a scenario where a try is opened, then a catch for that try appears before the throw, so that try is closed. Then later another try is opened, then throw. So only the second try is active. So our condition only includes the second try because its try_line < throw_line < catch_line, and the first try fails catch_line < throw_line. So correct.
Now, potential issue: In our mapping, we store catch_info for all tries. But when we iterate over catch_info, we check condition t_line < throw_line < c_line. This works. However, consider a try that is opened before throw but its catch is also before throw; that try is not active. Our condition excludes it because throw_line < c_line false. So fine.
Now, what about a try that is opened after throw? t_line < throw_line false, so excluded.
Thus candidates are exactly the active tries with matching type.
Now, one more nuance: The catch_info dict includes entries for tries that we popped. But what about tries that are never closed? Not possible.
Now, final answer.
I'll now produce final output.
But wait: There is a potential bug: When we parse catch, we pop from stack. However, the stack contains the line numbers of tries that have been encountered but not yet closed. But what if there are empty lines before a catch? We skip them, so the stack still correct. However, what if there are lines with no operator but they contain something like spaces? We skip. That's fine.
But consider the possibility of a line that contains "try" but with leading spaces, we still push. That's fine.
Now, double-check that the input reading: The first line contains integer n. The next n lines may contain empty lines or spaces. We read exactly n lines via input() calls. That's correct.
Now, final code ready.
But wait, we need to ensure we handle the case where the throw appears before any catch and there is a try that starts before throw and its catch after throw, but the catch type matches. That is standard.
Now, also note: The program may contain multiple try blocks with same catch type, and the throw is inside several of them. The innermost will be chosen. Our code picks smallest catch_line. So correct.
Now, we should also test with a scenario where the innermost matching catch is not the one with smallest catch_line because of some weird nesting? Let's check: In proper nesting, inner blocks always have smaller catch_line than outer blocks (since they close earlier). Indeed, if block A encloses block B, then try_A < try_B < catch_B < catch_A. So catch_B < catch_A. So inner has smaller catch_line. So min catch_line is innermost.
Thus consistent.
Now, everything is good.
But hold on: What about overlapping blocks that are not nested but sequential? They cannot both be active. So no issue.
Now, final code.
One more thought: The problem states "the program contains exactly one throw operator." So we can rely on that.
Now, the input size is up to 1e5 lines, but each line is short. Our code uses O(n) time.
Now, finalize.
Potential improvements: Use sys.stdout.write for output. But print is fine.
Now, provide final solution.
But before concluding, let's test some edge cases.
Edge case: n=5:
1: try
2: try
3: throw(A)
4: catch(B,"b")
5: catch(A,"a")
Active tries: try1 and try2? Check: try1 (1<3<5) true; try2 (2<3<4) true. Both active. Types: try2 catch type B, try1 catch type A. Only try1 matches. Output "a". That's correct because inner doesn't match.
Now, what about a try block with catch that appears on same line? Not allowed.
Now, handle blank lines: e.g.,
4
try
throw(A)
catch(A,"msg")
Line numbers: 1 try, 2 empty, 3 throw, 4 catch. Our code: i=1 try push; i=2 stripped empty skip; i=3 throw record; i=4 catch pop try1 store. Candidate: try1 (1<3<4) true, type match -> output "msg". Good.
Now, test with message containing quotes? Not allowed.
Now, code done.
But there is a subtlety: The catch operator's message is a string in quotes; however, the quotes may be escaped? The problem doesn't mention escape sequences. So we assume no.
Now, final answer.
I'll produce the final code with comments. ```python
import sys
def main():
input = sys.stdin.readline
code
n_line = input()
if not n_line:
return
n = int(n_line.strip())
# Stack of line numbers of unclosed 'try' operators
stack = []
# For each try (by its line number) store (exception_type, message, catch_line)
catch_info = {}
throw_line = None
throw_type = None
for i in range(1, n + 1):
line = input()
stripped = line.strip()
# Empty lines (or only spaces) contain no operator
if not stripped:
continue
if stripped == "try":
stack.append(i)
elif stripped.startswith("catch"):
# Parse "catch(<type>, "<message>")"
s = stripped
l = s.find('(')
r = s.rfind(')')
if l == -1 or r == -1: # should not happen
continue
inner = s[l + 1:r].strip()
comma = inner.find(',')
if comma == -1:
continue
exc = inner[:comma].strip()
msg_quoted = inner[comma + 1:].strip()
# Remove the surrounding double quotes
if len(msg_quoted) >= 2 and msg_quoted[0] == '"' and msg_quoted[-1] == '"':
msg = msg_quoted[1:-1]
else:
msg = msg_quoted # fallback (guaranteed to have quotes, though)
if not stack: # should not happen
continue
t = stack.pop()
catch_info[t] = (exc, msg, i)
elif stripped.startswith("throw"):
# Parse "throw(<type>)"
s = stripped
l = s.find('(')
r = s.rfind(')')
if l != -1 and r != -1:
exc = s[l + 1:r].strip()
throw_line = i
throw_type = exc
# Exactly one throw is guaranteed
if throw_line is None:
print("Unhandled Exception")
return
# Among all try-catch blocks that are active at the throw and have matching type,
# choose the one with the smallest catch line number (earliest catch).
best_msg = None
best_catch_line = None
for t_line, (c_type, msg, c_line) in catch_info.items():
if t_line < throw_line < c_line and c_type == throw_type:
if best_catch_line is None or c_line < best_catch_line:
best_catch_line = c_line
best_msg = msg
if best_msg is None:
print("Unhandled Exception")
else:
print(best_msg)